diff options
Diffstat (limited to 'StoneIsland')
500 files changed, 69725 insertions, 0 deletions
diff --git a/StoneIsland/config.xml b/StoneIsland/config.xml new file mode 100644 index 00000000..b57b1693 --- /dev/null +++ b/StoneIsland/config.xml @@ -0,0 +1,28 @@ +<?xml version='1.0' encoding='utf-8'?> +<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> + <name>StoneIsland</name> + <description> + Stone Island app + </description> + <author email="frontdesk@okfoc.us" href="http://okfoc.us/"> + OKFocus + </author> + <content src="index.html" /> + <plugin name="cordova-plugin-whitelist" version="1" /> + <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:*" /> + <platform name="android"> + <allow-intent href="market:*" /> + </platform> + <platform name="ios"> + <allow-intent href="itms:*" /> + <allow-intent href="itms-apps:*" /> + <preference name="BackupWebStorage" value="local"/> + <preference name="KeyboardDisplayRequiresUserAction" value="false"/> + </platform> +</widget> diff --git a/StoneIsland/hooks/README.md b/StoneIsland/hooks/README.md new file mode 100644 index 00000000..62e58b48 --- /dev/null +++ b/StoneIsland/hooks/README.md @@ -0,0 +1,196 @@ +<!-- +# +# 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 Hooks + +Cordova Hooks represent special scripts which could be added by application and plugin developers or even by your own build system to customize cordova commands. Hook scripts could be defined by adding them to the special predefined folder (`/hooks`) or via configuration files (`config.xml` and `plugin.xml`) and run serially in the following order: +* Application hooks from `/hooks`; +* Application hooks from `config.xml`; +* Plugin hooks from `plugins/.../plugin.xml`. + +__Remember__: Make your scripts executable. + +__Note__: `.cordova/hooks` directory is also supported for backward compatibility, but we don't recommend using it as it is deprecated. + +## Supported hook types +The following hook types are supported: + + after_build/ + after_compile/ + after_docs/ + after_emulate/ + after_platform_add/ + after_platform_rm/ + after_platform_ls/ + after_plugin_add/ + after_plugin_ls/ + after_plugin_rm/ + after_plugin_search/ + after_plugin_install/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being installed + after_prepare/ + after_run/ + after_serve/ + before_build/ + before_compile/ + before_docs/ + before_emulate/ + before_platform_add/ + before_platform_rm/ + before_platform_ls/ + before_plugin_add/ + before_plugin_ls/ + before_plugin_rm/ + before_plugin_search/ + before_plugin_install/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being installed + before_plugin_uninstall/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being uninstalled + before_prepare/ + before_run/ + before_serve/ + pre_package/ <-- Windows 8 and Windows Phone only. + +## Ways to define hooks +### Via '/hooks' directory +To execute custom action when corresponding hook type is fired, use hook type as a name for a subfolder inside 'hooks' directory and place you script file here, for example: + + # script file will be automatically executed after each build + hooks/after_build/after_build_custom_action.js + + +### Config.xml + +Hooks can be defined in project's `config.xml` using `<hook>` elements, for example: + + <hook type="before_build" src="scripts/appBeforeBuild.bat" /> + <hook type="before_build" src="scripts/appBeforeBuild.js" /> + <hook type="before_plugin_install" src="scripts/appBeforePluginInstall.js" /> + + <platform name="wp8"> + <hook type="before_build" src="scripts/wp8/appWP8BeforeBuild.bat" /> + <hook type="before_build" src="scripts/wp8/appWP8BeforeBuild.js" /> + <hook type="before_plugin_install" src="scripts/wp8/appWP8BeforePluginInstall.js" /> + ... + </platform> + + <platform name="windows8"> + <hook type="before_build" src="scripts/windows8/appWin8BeforeBuild.bat" /> + <hook type="before_build" src="scripts/windows8/appWin8BeforeBuild.js" /> + <hook type="before_plugin_install" src="scripts/windows8/appWin8BeforePluginInstall.js" /> + ... + </platform> + +### Plugin hooks (plugin.xml) + +As a plugin developer you can define hook scripts using `<hook>` elements in a `plugin.xml` like that: + + <hook type="before_plugin_install" src="scripts/beforeInstall.js" /> + <hook type="after_build" src="scripts/afterBuild.js" /> + + <platform name="wp8"> + <hook type="before_plugin_install" src="scripts/wp8BeforeInstall.js" /> + <hook type="before_build" src="scripts/wp8BeforeBuild.js" /> + ... + </platform> + +`before_plugin_install`, `after_plugin_install`, `before_plugin_uninstall` plugin hooks will be fired exclusively for the plugin being installed/uninstalled. + +## Script Interface + +### Javascript + +If you are writing hooks in Javascript you should use the following module definition: +```javascript +module.exports = function(context) { + ... +} +``` + +You can make your scipts async using Q: +```javascript +module.exports = function(context) { + var Q = context.requireCordovaModule('q'); + var deferral = new Q.defer(); + + setTimeout(function(){ + console.log('hook.js>> end'); + deferral.resolve(); + }, 1000); + + return deferral.promise; +} +``` + +`context` object contains hook type, executed script full path, hook options, command-line arguments passed to Cordova and top-level "cordova" object: +```json +{ + "hook": "before_plugin_install", + "scriptLocation": "c:\\script\\full\\path\\appBeforePluginInstall.js", + "cmdLine": "The\\exact\\command\\cordova\\run\\with arguments", + "opts": { + "projectRoot":"C:\\path\\to\\the\\project", + "cordova": { + "platforms": ["wp8"], + "plugins": ["com.plugin.withhooks"], + "version": "0.21.7-dev" + }, + "plugin": { + "id": "com.plugin.withhooks", + "pluginInfo": { + ... + }, + "platform": "wp8", + "dir": "C:\\path\\to\\the\\project\\plugins\\com.plugin.withhooks" + } + }, + "cordova": {...} +} + +``` +`context.opts.plugin` object will only be passed to plugin hooks scripts. + +You can also require additional Cordova modules in your script using `context.requireCordovaModule` in the following way: +```javascript +var Q = context.requireCordovaModule('q'); +``` + +__Note__: new module loader script interface is used for the `.js` files defined via `config.xml` or `plugin.xml` only. +For compatibility reasons hook files specified via `/hooks` folders are run via Node child_process spawn, see 'Non-javascript' section below. + +### Non-javascript + +Non-javascript scripts are run via Node child_process spawn from the project's root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables: + +* CORDOVA_VERSION - The version of the Cordova-CLI. +* CORDOVA_PLATFORMS - Comma separated list of platforms that the command applies to (e.g.: android, ios). +* CORDOVA_PLUGINS - Comma separated list of plugin IDs that the command applies to (e.g.: org.apache.cordova.file, org.apache.cordova.file-transfer) +* CORDOVA_HOOK - Path to the hook that is being executed. +* CORDOVA_CMDLINE - The exact command-line arguments passed to cordova (e.g.: cordova run ios --emulate) + +If a script returns a non-zero exit code, then the parent cordova command will be aborted. + +## Writing hooks + +We highly recommend writing your hooks using Node.js so that they are +cross-platform. Some good examples are shown here: + +[http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/](http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/) + +Also, note that even if you are working on Windows, and in case your hook scripts aren't bat files (which is recommended, if you want your scripts to work in non-Windows operating systems) Cordova CLI will expect a shebang line as the first line for it to know the interpreter it needs to use to launch the script. The shebang line should match the following example: + + #!/usr/bin/env [name_of_interpreter_executable] diff --git a/StoneIsland/platforms/ios/.gitignore b/StoneIsland/platforms/ios/.gitignore new file mode 100644 index 00000000..cc76483f --- /dev/null +++ b/StoneIsland/platforms/ios/.gitignore @@ -0,0 +1,5 @@ +*.mode1v3 +*.perspectivev3 +*.pbxuser +.DS_Store +build/ diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDV.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDV.h new file mode 100644 index 00000000..6cf592a0 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDV.h @@ -0,0 +1,41 @@ +/* + 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 "CDVPlugin.h" +#import "CDVViewController.h" +#import "CDVCommandDelegate.h" +#import "CDVURLProtocol.h" +#import "CDVInvokedUrlCommand.h" + +#import "CDVDebug.h" +#import "CDVPluginResult.h" +#import "CDVWhitelist.h" +#import "CDVLocalStorage.h" +#import "CDVScreenOrientationDelegate.h" +#import "CDVTimer.h" + +#import "NSArray+Comparisons.h" +#import "NSData+Base64.h" +#import "NSDictionary+Extensions.h" +#import "NSMutableArray+QueueAdditions.h" +#import "UIDevice+Extensions.h" + +#import "CDVJSON.h" diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVAvailability.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVAvailability.h new file mode 100644 index 00000000..71e20b97 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVAvailability.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 "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_NA 99999 /* not available */ + +/* + #if CORDOVA_VERSION_MIN_REQUIRED >= __CORDOVA_1_7_0 + // do something when its at least 1.7.0 + #else + // do something else (non 1.7.0) + #endif + */ +#ifndef CORDOVA_VERSION_MIN_REQUIRED + #define CORDOVA_VERSION_MIN_REQUIRED __CORDOVA_3_8_0 +#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) +#endif diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVAvailabilityDeprecated.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVAvailabilityDeprecated.h new file mode 100644 index 00000000..216b4c1d --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVAvailabilityDeprecated.h @@ -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 <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())) +#endif + +static inline BOOL CDV_IsIPad(void) CDV_DEPRECATED(3.7.0, "This will be removed in 4.0.0"); +static inline BOOL CDV_IsIPhone5(void) CDV_DEPRECATED(3.7.0, "This will be removed in 4.0.0"); + +static inline BOOL CDV_IsIPad(void) { + return [[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad; +} + +static inline BOOL CDV_IsIPhone5(void) { + return ([[UIScreen mainScreen] bounds].size.width == 568 && [[UIScreen mainScreen] bounds].size.height == 320) || ([[UIScreen mainScreen] bounds].size.height == 568 && [[UIScreen mainScreen] bounds].size.width == 320); +}
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegate.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegate.h new file mode 100644 index 00000000..04df6bc7 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegate.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 "CDVAvailability.h" +#import "CDVInvokedUrlCommand.h" + +@class CDVPlugin; +@class CDVPluginResult; +@class CDVWhitelist; + +@protocol CDVCommandDelegate <NSObject> + +@property (nonatomic, readonly) NSDictionary* settings; + +- (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 (^)())block; +// Returns the User-Agent of the associated UIWebView. +- (NSString*)userAgent; +// Returns whether the given URL passes the white-list. +- (BOOL)URLIsWhitelisted:(NSURL*)url; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegateImpl.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegateImpl.h new file mode 100644 index 00000000..05311343 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegateImpl.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegateImpl.m new file mode 100644 index 00000000..9407e0a8 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandDelegateImpl.m @@ -0,0 +1,180 @@ +/* + 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 + +- (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)]); + NSString* commandsJSON = [_viewController.webView stringByEvaluatingJavaScriptFromString:js]; + if ([commandsJSON length] > 0) { + CDV_EXEC_LOG(@"Exec: Retrieved new exec messages by chaining."); + } + + [_commandQueue enqueueCommandBatch:commandsJSON]; + [_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]; + + NSString* js = [NSString stringWithFormat:@"cordova.require('cordova/exec').nativeCallback('%@',%d,%@,%d)", callbackId, status, argumentsAsJSON, keepCallback]; + + [self evalJsHelper:js]; +} + +- (void)evalJs:(NSString*)js +{ + [self evalJs:js scheduledOnRunLoop:YES]; +} + +- (void)evalJs:(NSString*)js scheduledOnRunLoop:(BOOL)scheduledOnRunLoop +{ + js = [NSString stringWithFormat:@"cordova.require('cordova/exec').nativeEvalAndFetch(function(){%@})", js]; + if (scheduledOnRunLoop) { + [self evalJsHelper:js]; + } else { + [self evalJsHelper2:js]; + } +} + +- (id)getCommandInstance:(NSString*)pluginName +{ + return [_viewController getCommandInstance:pluginName]; +} + +- (void)runInBackground:(void (^)())block +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block); +} + +- (NSString*)userAgent +{ + return [_viewController userAgent]; +} + +- (BOOL)URLIsWhitelisted:(NSURL*)url +{ + return ![_viewController.whitelist schemeIsAllowed:[url scheme]] || + [_viewController.whitelist URLIsAllowed:url logFailure:NO]; +} + +- (NSDictionary*)settings +{ + return _viewController.settings; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandQueue.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandQueue.h new file mode 100644 index 00000000..3329078a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandQueue.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 <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)processXhrExecBridgePoke:(NSNumber*)requestId; +- (void)fetchCommandsFromJs; +- (void)executePending; +- (BOOL)execute:(CDVInvokedUrlCommand*)command; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandQueue.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandQueue.m new file mode 100644 index 00000000..48264b2a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVCommandQueue.m @@ -0,0 +1,211 @@ +/* + 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 "CDV.h" +#import "CDVCommandQueue.h" +#import "CDVViewController.h" +#import "CDVCommandDelegateImpl.h" +#import "CDVJSON_private.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)processXhrExecBridgePoke:(NSNumber*)requestId +{ + NSInteger rid = [requestId integerValue]; + + // An ID of 1 is a special case because that signifies the first request of + // the page. Since resetRequestId is called from webViewDidStartLoad, and the + // JS context at the time of webViewDidStartLoad is still that of the previous + // page, it's possible for requests from the previous page to come in after this + // point. We ignore these by enforcing that ID=1 be the first ID. + if ((_lastCommandQueueFlushRequestId == 0) && (rid != 1)) { + CDV_EXEC_LOG(@"Exec: Ignoring exec request from previous page."); + return; + } + + // Use the request ID to determine if we've already flushed for this request. + // This is required only because the NSURLProtocol enqueues the same request + // multiple times. + if (rid > _lastCommandQueueFlushRequestId) { + _lastCommandQueueFlushRequestId = [requestId integerValue]; + [self fetchCommandsFromJs]; + [self executePending]; + } +} + +- (void)fetchCommandsFromJs +{ + // Grab all the queued commands from the JS side. + NSString* queuedCommandsJSON = [_viewController.webView stringByEvaluatingJavaScriptFromString: + @"cordova.require('cordova/exec').nativeFetchMessages()"]; + + CDV_EXEC_LOG(@"Exec: Flushed JS->native queue (hadCommands=%d).", [queuedCommandsJSON length] > 0); + [self enqueueCommandBatch:queuedCommandsJSON]; +} + +- (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 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; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVConfigParser.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVConfigParser.h new file mode 100644 index 00000000..2e06c88f --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVConfigParser.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 CDVConfigParser : NSObject <NSXMLParserDelegate> +{ + NSString* featureName; +} + +@property (nonatomic, readonly, strong) NSMutableDictionary* pluginsDict; +@property (nonatomic, readonly, strong) NSMutableDictionary* settings; +@property (nonatomic, readonly, strong) NSMutableArray* whitelistHosts; +@property (nonatomic, readonly, strong) NSMutableArray* startupPluginNames; +@property (nonatomic, readonly, strong) NSString* startPage; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVConfigParser.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVConfigParser.m new file mode 100644 index 00000000..4b73b60a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVConfigParser.m @@ -0,0 +1,88 @@ +/* + 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* whitelistHosts; +@property (nonatomic, readwrite, strong) NSMutableArray* startupPluginNames; +@property (nonatomic, readwrite, strong) NSString* startPage; + +@end + +@implementation CDVConfigParser + +@synthesize pluginsDict, settings, whitelistHosts, startPage, startupPluginNames; + +- (id)init +{ + self = [super init]; + if (self != nil) { + self.pluginsDict = [[NSMutableDictionary alloc] initWithCapacity:30]; + self.settings = [[NSMutableDictionary alloc] initWithCapacity:30]; + self.whitelistHosts = [[NSMutableArray alloc] initWithCapacity:30]; + [self.whitelistHosts addObject:@"file:///*"]; + [self.whitelistHosts addObject:@"content:///*"]; + [self.whitelistHosts addObject:@"data:///*"]; + 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:@"access"]) { + [whitelistHosts addObject:attributeDict[@"origin"]]; + } else if ([elementName isEqualToString:@"content"]) { + self.startPage = attributeDict[@"src"]; + } +} + +- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName +{ + if ([elementName isEqualToString:@"feature"]) { // no longer handling a feature so release + featureName = nil; + } +} + +- (void)parser:(NSXMLParser*)parser parseErrorOccurred:(NSError*)parseError +{ + NSAssert(NO, @"config.xml parse error line %ld col %ld", (long)[parser lineNumber], (long)[parser columnNumber]); +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVDebug.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVDebug.h new file mode 100644 index 00000000..4a0d9f92 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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/StoneIsland/platforms/ios/CordovaLib/Classes/CDVHandleOpenURL.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVHandleOpenURL.h new file mode 100644 index 00000000..24f461f3 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVHandleOpenURL.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 "CDVPlugin.h" + +@interface CDVHandleOpenURL : CDVPlugin + +@property (nonatomic, strong) NSURL* url; +@property (nonatomic, assign) BOOL pageLoaded; + +@end + diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVHandleOpenURL.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVHandleOpenURL.m new file mode 100644 index 00000000..e5dcdd5a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVHandleOpenURL.m @@ -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 "CDVHandleOpenURL.h" +#import "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 +{ + if (!pageLoaded) { + // query the webview for readystate + NSString* readyState = [self.webView stringByEvaluatingJavaScriptFromString:@"document.readyState"]; + pageLoaded = [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"]; + } + + if (pageLoaded) { + // calls into javascript global function 'handleOpenURL' + NSString* jsString = [NSString stringWithFormat:@"document.addEventListener('deviceready',function(){if (typeof handleOpenURL === 'function') { handleOpenURL(\"%@\");}});", url]; + [self.webView stringByEvaluatingJavaScriptFromString:jsString]; + } else { + // save for when page has loaded + self.url = url; + } +} + + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVInvokedUrlCommand.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVInvokedUrlCommand.h new file mode 100644 index 00000000..993e0a28 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVInvokedUrlCommand.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVInvokedUrlCommand.m new file mode 100644 index 00000000..3a5e8e75 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVInvokedUrlCommand.m @@ -0,0 +1,117 @@ +/* + 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" +#import "NSData+Base64.h" + +@implementation CDVInvokedUrlCommand + +@synthesize arguments = _arguments; +@synthesize callbackId = _callbackId; +@synthesize className = _className; +@synthesize methodName = _methodName; + ++ (CDVInvokedUrlCommand*)commandFromJson:(NSArray*)jsonEntry +{ + return [[CDVInvokedUrlCommand alloc] initFromJson:jsonEntry]; +} + +- (id)initFromJson:(NSArray*)jsonEntry +{ + id tmp = [jsonEntry objectAtIndex:0]; + NSString* callbackId = tmp == [NSNull null] ? nil : tmp; + NSString* className = [jsonEntry objectAtIndex:1]; + NSString* methodName = [jsonEntry objectAtIndex:2]; + NSMutableArray* arguments = [jsonEntry objectAtIndex:3]; + + return [self initWithArguments:arguments + callbackId:callbackId + className:className + methodName:methodName]; +} + +- (id)initWithArguments:(NSArray*)arguments + callbackId:(NSString*)callbackId + className:(NSString*)className + methodName:(NSString*)methodName +{ + self = [super init]; + if (self != nil) { + _arguments = arguments; + _callbackId = callbackId; + _className = className; + _methodName = methodName; + } + [self massageArguments]; + return self; +} + +- (void)massageArguments +{ + NSMutableArray* newArgs = nil; + + for (NSUInteger i = 0, count = [_arguments count]; i < count; ++i) { + id arg = [_arguments objectAtIndex:i]; + if (![arg isKindOfClass:[NSDictionary class]]) { + continue; + } + NSDictionary* dict = arg; + NSString* type = [dict objectForKey:@"CDVType"]; + if (!type || ![type isEqualToString:@"ArrayBuffer"]) { + continue; + } + NSString* data = [dict objectForKey:@"data"]; + if (!data) { + continue; + } + if (newArgs == nil) { + newArgs = [NSMutableArray arrayWithArray:_arguments]; + _arguments = newArgs; + } + [newArgs replaceObjectAtIndex:i withObject:[NSData cdv_dataFromBase64String:data]]; + } +} + +- (id)argumentAtIndex:(NSUInteger)index +{ + return [self argumentAtIndex:index withDefault:nil]; +} + +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue +{ + return [self argumentAtIndex:index withDefault:defaultValue andClass:nil]; +} + +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue andClass:(Class)aClass +{ + if (index >= [_arguments count]) { + return defaultValue; + } + id ret = [_arguments objectAtIndex:index]; + if (ret == [NSNull null]) { + ret = defaultValue; + } + if ((aClass != nil) && ![ret isKindOfClass:aClass]) { + ret = defaultValue; + } + return ret; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON.h new file mode 100644 index 00000000..ede708f9 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON.h @@ -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 "CDVAvailabilityDeprecated.h" + +@interface NSArray (CDVJSONSerializing) +- (NSString*)JSONString CDV_DEPRECATED(3.8 .0, "Use NSJSONSerialization instead."); + +@end + +@interface NSDictionary (CDVJSONSerializing) +- (NSString*)JSONString CDV_DEPRECATED(3.8 .0, "Use NSJSONSerialization instead."); + +@end + +@interface NSString (CDVJSONSerializing) +- (id)JSONObject CDV_DEPRECATED(3.8 .0, "Use NSJSONSerialization instead."); + +- (id)JSONFragment CDV_DEPRECATED(3.8 .0, "Use NSJSONSerialization instead."); + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON.m new file mode 100644 index 00000000..85db545a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON.m @@ -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 "CDVJSON_private.h" + +@implementation NSArray (CDVJSONSerializing) + +- (NSString*)JSONString +{ + return [self cdv_JSONString]; +} + +@end + +@implementation NSDictionary (CDVJSONSerializing) + +- (NSString*)JSONString +{ + return [self cdv_JSONString]; +} + +@end + +@implementation NSString (CDVJSONSerializing) + +- (id)JSONObject +{ + return [self cdv_JSONObject]; +} + +- (id)JSONFragment +{ + return [self cdv_JSONFragment]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON_private.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON_private.h new file mode 100644 index 00000000..afb5cc66 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON_private.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON_private.m new file mode 100644 index 00000000..53856806 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVJSON_private.m @@ -0,0 +1,91 @@ +/* + 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 +{ + 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 +{ + 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 +{ + NSError* error = nil; + id object = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + + if (error != nil) { + NSLog(@"NSString JSONObject error: %@", [error localizedDescription]); + } + + return object; +} + +- (id)cdv_JSONFragment +{ + 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; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVLocalStorage.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVLocalStorage.h new file mode 100644 index 00000000..dec6ab3b --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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 "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; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVLocalStorage.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVLocalStorage.m new file mode 100644 index 00000000..8aec403b --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVLocalStorage.m @@ -0,0 +1,492 @@ +/* + 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 "CDV.h" + +@interface CDVLocalStorage () + +@property (nonatomic, readwrite, strong) NSMutableArray* backupInfo; // array of CDVBackupInfo objects +@property (nonatomic, readwrite, weak) id <UIWebViewDelegate> webviewDelegate; + +@end + +@implementation CDVLocalStorage + +@synthesize backupInfo, webviewDelegate; + +- (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 +{ + NSAssert(IsAtLeastiOSVersion(@"5.1"), @"Cannot mark files for NSURLIsExcludedFromBackupKey on iOS less than 5.1"); + + 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. + if (!IsAtLeastiOSVersion(@"6.0")) { + return; + } + + 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]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPlugin.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPlugin.h new file mode 100644 index 00000000..5e8b2830 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPlugin.h @@ -0,0 +1,67 @@ +/* + 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" + +extern NSString* const CDVPageDidLoadNotification; +extern NSString* const CDVPluginHandleOpenURLNotification; +extern NSString* const CDVPluginResetNotification; +extern NSString* const CDVLocalNotification; +extern NSString* const CDVRemoteNotification; +extern NSString* const CDVRemoteNotificationError; + +@interface CDVPlugin : NSObject {} + +@property (nonatomic, weak) UIWebView* webView; +@property (nonatomic, weak) UIViewController* viewController; +@property (nonatomic, weak) id <CDVCommandDelegate> commandDelegate; + +@property (readonly, assign) BOOL hasPendingOperation; + +- (CDVPlugin*)initWithWebView:(UIWebView*)theWebView; +- (void)pluginInitialize; + +- (void)handleOpenURL:(NSNotification*)notification; +- (void)onAppTerminate; +- (void)onMemoryWarning; +- (void)onReset; +- (void)dispose; + +/* + // see initWithWebView implementation + - (void) onPause {} + - (void) onResume {} + - (void) onOrientationWillChange {} + - (void) onOrientationDidChange {} + - (void)didReceiveLocalNotification:(NSNotification *)notification; + */ + +- (id)appDelegate; + +- (NSString*)writeJavascript:(NSString*)javascript CDV_DEPRECATED(3.6, "Use the CDVCommandDelegate equivalent of evalJs:. This will be removed in 4.0.0"); + +- (NSString*)success:(CDVPluginResult*)pluginResult callbackId:(NSString*)callbackId CDV_DEPRECATED(3.6, "Use the CDVCommandDelegate equivalent of sendPluginResult:callbackId. This will be removed in 4.0.0"); + +- (NSString*)error:(CDVPluginResult*)pluginResult callbackId:(NSString*)callbackId CDV_DEPRECATED(3.6, "Use the CDVCommandDelegate equivalent of sendPluginResult:callbackId. This will be removed in 4.0.0"); + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPlugin.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPlugin.m new file mode 100644 index 00000000..ea81ddd1 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPlugin.m @@ -0,0 +1,154 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVPlugin.h" + +NSString* const CDVPageDidLoadNotification = @"CDVPageDidLoadNotification"; +NSString* const CDVPluginHandleOpenURLNotification = @"CDVPluginHandleOpenURLNotification"; +NSString* const CDVPluginResetNotification = @"CDVPluginResetNotification"; +NSString* const CDVLocalNotification = @"CDVLocalNotification"; +NSString* const CDVRemoteNotification = @"CDVRemoteNotification"; +NSString* const CDVRemoteNotificationError = @"CDVRemoteNotificationError"; + +@interface CDVPlugin () + +@property (readwrite, assign) BOOL hasPendingOperation; + +@end + +@implementation CDVPlugin +@synthesize webView, viewController, commandDelegate, hasPendingOperation; + +// Do not override these methods. Use pluginInitialize instead. +- (CDVPlugin*)initWithWebView:(UIWebView*)theWebView settings:(NSDictionary*)classSettings +{ + return [self initWithWebView:theWebView]; +} + +- (CDVPlugin*)initWithWebView:(UIWebView*)theWebView +{ + self = [super init]; + if (self) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppTerminate) name:UIApplicationWillTerminateNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:CDVPluginHandleOpenURLNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReset) name:CDVPluginResetNotification object:theWebView]; + + self.webView = theWebView; + } + return self; +} + +- (void)pluginInitialize +{ + // You can listen to more app notifications, see: + // http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006728-CH3-DontLinkElementID_4 + + // NOTE: if you want to use these, make sure you uncomment the corresponding notification handler + + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrientationWillChange) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrientationDidChange) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; + + // Added in 2.3.0 + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveLocalNotification:) name:CDVLocalNotification object:nil]; + + // Added in 2.5.0 + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageDidLoad:) name:CDVPageDidLoadNotification object:self.webView]; +} + +- (void)dispose +{ + viewController = nil; + commandDelegate = nil; + webView = nil; +} + +/* +// NOTE: for onPause and onResume, calls into JavaScript must not call or trigger any blocking UI, like alerts +- (void) onPause {} +- (void) onResume {} +- (void) onOrientationWillChange {} +- (void) onOrientationDidChange {} +*/ + +/* NOTE: calls into JavaScript must not call or trigger any blocking UI, like alerts */ +- (void)handleOpenURL:(NSNotification*)notification +{ + // override to handle urls sent to your app + // register your url schemes in your App-Info.plist + + NSURL* url = [notification object]; + + if ([url isKindOfClass:[NSURL class]]) { + /* Do your thing! */ + } +} + +/* NOTE: calls into JavaScript must not call or trigger any blocking UI, like alerts */ +- (void)onAppTerminate +{ + // override this if you need to do any cleanup on app exit +} + +- (void)onMemoryWarning +{ + // override to remove caches, etc +} + +- (void)onReset +{ + // Override to cancel any long-running requests when the WebView navigates or refreshes. +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; // this will remove all notification unless added using addObserverForName:object:queue:usingBlock: +} + +- (id)appDelegate +{ + return [[UIApplication sharedApplication] delegate]; +} + +- (NSString*)writeJavascript:(NSString*)javascript +{ + return [self.webView stringByEvaluatingJavaScriptFromString:javascript]; +} + +- (NSString*)success:(CDVPluginResult*)pluginResult callbackId:(NSString*)callbackId +{ + [self.commandDelegate evalJs:[pluginResult toSuccessCallbackString:callbackId]]; + return @""; +} + +- (NSString*)error:(CDVPluginResult*)pluginResult callbackId:(NSString*)callbackId +{ + [self.commandDelegate evalJs:[pluginResult toErrorCallbackString:callbackId]]; + return @""; +} + +// default implementation does nothing, ideally, we are not registered for notification if we aren't going to do anything. +// - (void)didReceiveLocalNotification:(NSNotification *)notification +// { +// // UILocalNotification* localNotification = [notification object]; // get the payload as a LocalNotification +// } + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPluginResult.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPluginResult.h new file mode 100644 index 00000000..e624d4de --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPluginResult.h @@ -0,0 +1,71 @@ +/* + 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 enum { + CDVCommandStatus_NO_RESULT = 0, + CDVCommandStatus_OK, + CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION, + CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION, + CDVCommandStatus_INSTANTIATION_EXCEPTION, + CDVCommandStatus_MALFORMED_URL_EXCEPTION, + CDVCommandStatus_IO_EXCEPTION, + CDVCommandStatus_INVALID_ACTION, + CDVCommandStatus_JSON_EXCEPTION, + CDVCommandStatus_ERROR +} CDVCommandStatus; + +@interface CDVPluginResult : NSObject {} + +@property (nonatomic, strong, readonly) NSNumber* status; +@property (nonatomic, strong, readonly) id message; +@property (nonatomic, strong) NSNumber* keepCallback; +// 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 messageAsDouble:(double)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsBool:(BOOL)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDictionary:(NSDictionary*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArrayBuffer:(NSData*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsMultipart:(NSArray*)theMessages; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageToErrorObject:(int)errorCode; + ++ (void)setVerbose:(BOOL)verbose; ++ (BOOL)isVerbose; + +- (void)setKeepCallbackAsBool:(BOOL)bKeepCallback; + +- (NSString*)argumentsAsJSON; + +// These methods are used by the legacy plugin return result method +- (NSString*)toJSONString CDV_DEPRECATED(3.6, "Only used by toSuccessCallbackString and toErrorCallbackString which are deprecated. This will be removed in 4.0.0"); + +- (NSString*)toSuccessCallbackString:(NSString*)callbackId CDV_DEPRECATED(3.6, "Use the CDVCommandDelegate method sendPluginResult:callbackId instead. This will be removed in 4.0.0"); + +- (NSString*)toErrorCallbackString:(NSString*)callbackId CDV_DEPRECATED(3.6, "Use the CDVCommandDelegate method sendPluginResult:callbackId instead. This will be removed in 4.0.0"); + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPluginResult.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPluginResult.m new file mode 100644 index 00000000..13839efd --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVPluginResult.m @@ -0,0 +1,224 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVPluginResult.h" +#import "CDVJSON_private.h" +#import "CDVDebug.h" +#import "NSData+Base64.h" + +@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 cdv_base64EncodedString] + }; +} + +id massageMessage(id message) +{ + if ([message isKindOfClass:[NSData class]]) { + return messageFromArrayBuffer(message); + } + return message; +} + +id messageFromMultipart(NSArray* theMessages) +{ + NSMutableArray* messages = [NSMutableArray arrayWithArray:theMessages]; + + for (NSUInteger i = 0; i < messages.count; ++i) { + [messages replaceObjectAtIndex:i withObject:massageMessage([messages objectAtIndex:i])]; + } + + return @{ + @"CDVType" : @"MultiPart", + @"messages" : messages + }; +} + ++ (void)initialize +{ + org_apache_cordova_CommandStatusMsgs = [[NSArray alloc] initWithObjects:@"No result", + @"OK", + @"Class not found", + @"Illegal access", + @"Instantiation error", + @"Malformed url", + @"IO error", + @"Invalid action", + @"JSON error", + @"Error", + nil]; +} + +- (CDVPluginResult*)init +{ + return [self initWithStatus:CDVCommandStatus_NO_RESULT message:nil]; +} + +- (CDVPluginResult*)initWithStatus:(CDVCommandStatus)statusOrdinal message:(id)theMessage +{ + self = [super init]; + if (self) { + status = [NSNumber numberWithInt:statusOrdinal]; + message = theMessage; + keepCallback = [NSNumber numberWithBool:NO]; + } + return self; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal +{ + return [[self alloc] initWithStatus:statusOrdinal message: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 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; +} + +// These methods are used by the legacy plugin return result method +- (NSString*)toJSONString +{ + NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys: + self.status, @"status", + self.message ? self. message:[NSNull null], @"message", + self.keepCallback, @"keepCallback", + nil]; + + NSError* error = nil; + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict + options:NSJSONWritingPrettyPrinted + error:&error]; + NSString* resultString = nil; + + if (error != nil) { + NSLog(@"toJSONString error: %@", [error localizedDescription]); + } else { + resultString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + } + + if ([[self class] isVerbose]) { + NSLog(@"PluginResult:toJSONString - %@", resultString); + } + return resultString; +} + +- (NSString*)toSuccessCallbackString:(NSString*)callbackId +{ + NSString* successCB = [NSString stringWithFormat:@"cordova.callbackSuccess('%@',%@);", callbackId, [self toJSONString]]; + + if ([[self class] isVerbose]) { + NSLog(@"PluginResult toSuccessCallbackString: %@", successCB); + } + return successCB; +} + +- (NSString*)toErrorCallbackString:(NSString*)callbackId +{ + NSString* errorCB = [NSString stringWithFormat:@"cordova.callbackError('%@',%@);", callbackId, [self toJSONString]]; + + if ([[self class] isVerbose]) { + NSLog(@"PluginResult toErrorCallbackString: %@", errorCB); + } + return errorCB; +} + +static BOOL gIsVerbose = NO; ++ (void)setVerbose:(BOOL)verbose +{ + gIsVerbose = verbose; +} + ++ (BOOL)isVerbose +{ + return gIsVerbose; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVScreenOrientationDelegate.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVScreenOrientationDelegate.h new file mode 100644 index 00000000..7226205a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVScreenOrientationDelegate.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> + +@protocol CDVScreenOrientationDelegate <NSObject> + +- (NSUInteger)supportedInterfaceOrientations; +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; +- (BOOL)shouldAutorotate; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVShared.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVShared.h new file mode 100644 index 00000000..68acc5c2 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVShared.h @@ -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. + */ + +// This file was emptied out in 3.6.0 release (July 2014). +// It will be deleted in a future release. +#import <CoreLocation/CoreLocation.h> diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVTimer.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVTimer.h new file mode 100644 index 00000000..6d31593f --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVTimer.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVTimer.m new file mode 100644 index 00000000..784e94d3 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVURLProtocol.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVURLProtocol.h new file mode 100644 index 00000000..5444f6d1 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVURLProtocol.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> +#import "CDVAvailability.h" + +@class CDVViewController; + +@interface CDVURLProtocol : NSURLProtocol {} + ++ (void)registerViewController:(CDVViewController*)viewController; ++ (void)unregisterViewController:(CDVViewController*)viewController; +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVURLProtocol.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVURLProtocol.m new file mode 100644 index 00000000..fce5783a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVURLProtocol.m @@ -0,0 +1,213 @@ +/* + 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 "CDVWhitelist.h" +#import "CDVViewController.h" + +static CDVWhitelist* gWhitelist = nil; +// 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://"; + +// Returns the registered view controller that sent the given request. +// If the user-agent is not from a UIWebView, or if it's from an unregistered one, +// then nil is returned. +static CDVViewController *viewControllerForRequest(NSURLRequest* request) +{ + // The exec bridge explicitly sets the VC address in a header. + // This works around the User-Agent not being set for file: URLs. + NSString* addrString = [request valueForHTTPHeaderField:@"vc"]; + + if (addrString == nil) { + NSString* userAgent = [request valueForHTTPHeaderField:@"User-Agent"]; + if (userAgent == nil) { + return nil; + } + NSUInteger bracketLocation = [userAgent rangeOfString:@"(" options:NSBackwardsSearch].location; + if (bracketLocation == NSNotFound) { + return nil; + } + addrString = [userAgent substringFromIndex:bracketLocation + 1]; + } + + long long viewControllerAddress = [addrString longLongValue]; + @synchronized(gRegisteredControllers) { + if (![gRegisteredControllers containsObject:[NSNumber numberWithLongLong:viewControllerAddress]]) { + return nil; + } + } + + return (__bridge CDVViewController*)(void*)viewControllerAddress; +} + +@implementation CDVURLProtocol + ++ (void)registerPGHttpURLProtocol {} + ++ (void)registerURLProtocol {} + +// Called to register the URLProtocol, and to make it away of an instance of +// a ViewController. ++ (void)registerViewController:(CDVViewController*)viewController +{ + if (gRegisteredControllers == nil) { + [NSURLProtocol registerClass:[CDVURLProtocol class]]; + gRegisteredControllers = [[NSMutableSet alloc] initWithCapacity:8]; + // The whitelist doesn't change, so grab the first one and store it. + gWhitelist = viewController.whitelist; + + // Note that we grab the whitelist from the first viewcontroller for now - but this will change + // when we allow a registered viewcontroller to have its own whitelist (e.g InAppBrowser) + // Differentiating the requests will be through the 'vc' http header below as used for the js->objc bridge. + // The 'vc' value is generated by casting the viewcontroller object to a (long long) value (see CDVViewController::webViewDidFinishLoad) + if (gWhitelist == nil) { + NSLog(@"WARNING: NO whitelist has been set in CDVURLProtocol."); + } + } + + @synchronized(gRegisteredControllers) { + [gRegisteredControllers addObject:[NSNumber numberWithLongLong:(long long)viewController]]; + } +} + ++ (void)unregisterViewController:(CDVViewController*)viewController +{ + @synchronized(gRegisteredControllers) { + [gRegisteredControllers removeObject:[NSNumber numberWithLongLong:(long long)viewController]]; + } +} + ++ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest +{ + NSURL* theUrl = [theRequest URL]; + CDVViewController* viewController = viewControllerForRequest(theRequest); + + if ([[theUrl absoluteString] hasPrefix:kCDVAssetsLibraryPrefixes]) { + return YES; + } else if (viewController != nil) { + if ([[theUrl path] isEqualToString:@"/!gap_exec"]) { + NSString* queuedCommandsJSON = [theRequest valueForHTTPHeaderField:@"cmds"]; + NSString* requestId = [theRequest valueForHTTPHeaderField:@"rc"]; + if (requestId == nil) { + NSLog(@"!cordova request missing rc header"); + return NO; + } + BOOL hasCmds = [queuedCommandsJSON length] > 0; + if (hasCmds) { + SEL sel = @selector(enqueueCommandBatch:); + [viewController.commandQueue performSelectorOnMainThread:sel withObject:queuedCommandsJSON waitUntilDone:NO]; + [viewController.commandQueue performSelectorOnMainThread:@selector(executePending) withObject:nil waitUntilDone:NO]; + } else { + SEL sel = @selector(processXhrExecBridgePoke:); + [viewController.commandQueue performSelectorOnMainThread:sel withObject:[NSNumber numberWithInteger:[requestId integerValue]] waitUntilDone:NO]; + } + // Returning NO here would be 20% faster, but it spams WebInspector's console with failure messages. + // If JS->Native bridge speed is really important for an app, they should use the iframe bridge. + // Returning YES here causes the request to come through canInitWithRequest two more times. + // For this reason, we return NO when cmds exist. + return !hasCmds; + } + // we only care about http and https connections. + // CORS takes care of http: trying to access file: URLs. + if ([gWhitelist schemeIsAllowed:[theUrl scheme]]) { + // if it FAILS the whitelist, we return TRUE, so we can fail the connection later + return ![gWhitelist URLIsAllowed:theUrl]; + } + } + + 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 path] isEqualToString:@"/!gap_exec"]) { + [self sendResponseWithResponseCode:200 data:nil mimeType:nil]; + return; + } else 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 = [gWhitelist errorStringForURL: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]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVUserAgentUtil.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVUserAgentUtil.h new file mode 100644 index 00000000..4de382f0 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVUserAgentUtil.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVUserAgentUtil.m new file mode 100644 index 00000000..c3402d08 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVUserAgentUtil.m @@ -0,0 +1,122 @@ +/* + 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; + +@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; + NSString* systemAndLocale = [NSString stringWithFormat:@"%@ %@ %@", model, systemVersion, localeStr]; + + NSString* cordovaUserAgentVersion = [userDefaults stringForKey:kCdvUserAgentVersionKey]; + gOriginalUserAgent = [userDefaults stringForKey:kCdvUserAgentKey]; + BOOL cachedValueIsOld = ![systemAndLocale isEqualToString:cordovaUserAgentVersion]; + + if ((gOriginalUserAgent == nil) || cachedValueIsOld) { + UIWebView* sampleWebView = [[UIWebView alloc] initWithFrame:CGRectZero]; + 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 == 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)() = [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]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVViewController.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVViewController.h new file mode 100644 index 00000000..51863a59 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVViewController.h @@ -0,0 +1,84 @@ +/* + 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 "CDVWhitelist.h" +#import "CDVScreenOrientationDelegate.h" +#import "CDVPlugin.h" + +@interface CDVViewController : UIViewController <UIWebViewDelegate, CDVScreenOrientationDelegate>{ + @protected + id <CDVCommandDelegate> _commandDelegate; + @protected + CDVCommandQueue* _commandQueue; + NSString* _userAgent; +} + +@property (nonatomic, strong) IBOutlet UIWebView* 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, readonly, strong) CDVWhitelist* whitelist; // readonly for public +@property (nonatomic, readonly, assign) BOOL loadFromString; + +@property (nonatomic, readwrite, copy) NSString* wwwFolderName; +@property (nonatomic, readwrite, copy) NSString* startPage; +@property (nonatomic, readonly, strong) CDVCommandQueue* commandQueue; +@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; + ++ (NSDictionary*)getBundlePlist:(NSString*)plistName; ++ (NSString*)applicationDocumentsDirectory; + +- (void)printMultitaskingInfo; +- (void)createGapView; +- (UIWebView*)newCordovaViewWithFrame:(CGRect)bounds; + +- (void)javascriptAlert:(NSString*)text; +- (NSString*)appURLScheme; + +- (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; + +- (BOOL)URLisAllowed:(NSURL*)url; +- (void)processOpenUrl:(NSURL*)url; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVViewController.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVViewController.m new file mode 100644 index 00000000..6d81e8d9 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVViewController.m @@ -0,0 +1,1049 @@ +/* + 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 "CDVCommandDelegateImpl.h" +#import "CDVConfigParser.h" +#import "CDVUserAgentUtil.h" +#import "CDVWebViewDelegate.h" +#import <AVFoundation/AVFoundation.h> +#import "CDVHandleOpenURL.h" + +#define degreesToRadian(x) (M_PI * (x) / 180.0) + +@interface CDVViewController () { + NSInteger _userAgentLockToken; + CDVWebViewDelegate* _webViewDelegate; +} + +@property (nonatomic, readwrite, strong) NSXMLParser* configParser; +@property (nonatomic, readwrite, strong) NSMutableDictionary* settings; +@property (nonatomic, readwrite, strong) CDVWhitelist* whitelist; +@property (nonatomic, readwrite, strong) NSMutableDictionary* pluginObjects; +@property (nonatomic, readwrite, strong) NSArray* startupPluginNames; +@property (nonatomic, readwrite, strong) NSDictionary* pluginsMap; +@property (nonatomic, readwrite, strong) NSArray* supportedOrientations; +@property (nonatomic, readwrite, assign) BOOL loadFromString; + +@property (readwrite, assign) BOOL initialized; + +@property (atomic, strong) NSURL* openURL; + +@end + +@implementation CDVViewController + +@synthesize webView, supportedOrientations; +@synthesize pluginObjects, pluginsMap, whitelist, startupPluginNames; +@synthesize configParser, settings, loadFromString; +@synthesize wwwFolderName, startPage, initialized, openURL, baseUserAgent; +@synthesize commandDelegate = _commandDelegate; +@synthesize commandQueue = _commandQueue; + +- (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]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPageDidLoad:) + name:CDVPageDidLoadNotification 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; + + // load config.xml settings + [self loadSettings]; + } +} + +- (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)viewWillAppear:(BOOL)animated +{ + [super viewWillAppear:animated]; +} + +- (void)viewWillDisappear:(BOOL)animated +{ + [super viewWillDisappear:animated]; +} + +- (void)printVersion +{ + NSLog(@"Apache Cordova native platform version %@ is starting.", CDV_VERSION); +} + +- (void)printPlatformVersionWarning +{ + if (!IsAtLeastiOSVersion(@"6.0")) { + NSLog(@"CRITICAL: For Cordova 3.5.0 and above, you will need to upgrade to at least iOS 6.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"); +} + +- (BOOL)URLisAllowed:(NSURL*)url +{ + if (self.whitelist == nil) { + return YES; + } + + return [self.whitelist URLIsAllowed:url]; +} + +- (void)loadSettings +{ + CDVConfigParser* delegate = [[CDVConfigParser alloc] init]; + + // read from config.xml in the app bundle + NSString* path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"xml"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { + NSAssert(NO, @"ERROR: config.xml does not exist. Please run cordova-ios/bin/cordova_plist_to_config_xml path/to/project."); + return; + } + + NSURL* url = [NSURL fileURLWithPath:path]; + + configParser = [[NSXMLParser alloc] initWithContentsOfURL:url]; + if (configParser == nil) { + NSLog(@"Failed to initialize XML parser."); + return; + } + [configParser setDelegate:((id < NSXMLParserDelegate >)delegate)]; + [configParser parse]; + + // Get the plugin dictionary, whitelist and settings from the delegate. + self.pluginsMap = delegate.pluginsDict; + self.startupPluginNames = delegate.startupPluginNames; + self.whitelist = [[CDVWhitelist alloc] initWithArray:delegate.whitelistHosts]; + self.settings = delegate.settings; + + // And the start folder/page. + self.wwwFolderName = @"www"; + 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 { + // 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) { + self.loadFromString = YES; + 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 settingForKey:@"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; +} + +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad +{ + [super viewDidLoad]; + + // // Fix the iOS 5.1 SECURITY_ERR bug (CB-347), this must be before the webView is instantiated //// + + NSString* backupWebStorageType = @"cloud"; // default value + + id backupWebStorage = [self settingForKey:@"BackupWebStorage"]; + if ([backupWebStorage isKindOfClass:[NSString class]]) { + backupWebStorageType = backupWebStorage; + } + [self setSetting:backupWebStorageType forKey:@"BackupWebStorage"]; + + if (IsAtLeastiOSVersion(@"5.1")) { + [CDVLocalStorage __fixupDatabaseLocationsWithBackupType:backupWebStorageType]; + } + + // // Instantiate the WebView /////////////// + + if (!self.webView) { + [self createGapView]; + } + + // Configure WebView + _webViewDelegate = [[CDVWebViewDelegate alloc] initWithDelegate:self]; + self.webView.delegate = _webViewDelegate; + + // register this viewcontroller with the NSURLProtocol, only after the User-Agent is set + [CDVURLProtocol registerViewController:self]; + + // ///////////////// + + NSString* enableViewportScale = [self settingForKey:@"EnableViewportScale"]; + NSNumber* allowInlineMediaPlayback = [self settingForKey:@"AllowInlineMediaPlayback"]; + BOOL mediaPlaybackRequiresUserAction = YES; // default value + if ([self settingForKey:@"MediaPlaybackRequiresUserAction"]) { + mediaPlaybackRequiresUserAction = [(NSNumber*)[self settingForKey:@"MediaPlaybackRequiresUserAction"] boolValue]; + } + + self.webView.scalesPageToFit = [enableViewportScale boolValue]; + + /* + * 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. + */ + if (IsAtLeastiOSVersion(@"5.1") && (([backupWebStorageType isEqualToString:@"local"]) || + ([backupWebStorageType isEqualToString:@"cloud"] && !IsAtLeastiOSVersion(@"6.0")))) { + [self registerPlugin:[[CDVLocalStorage alloc] initWithWebView:self.webView] withClassName:NSStringFromClass([CDVLocalStorage class])]; + } + + /* + * This is for iOS 4.x, where you can allow inline <video> and <audio>, and also autoplay them + */ + if ([allowInlineMediaPlayback boolValue] && [self.webView respondsToSelector:@selector(allowsInlineMediaPlayback)]) { + self.webView.allowsInlineMediaPlayback = YES; + } + if ((mediaPlaybackRequiresUserAction == NO) && [self.webView respondsToSelector:@selector(mediaPlaybackRequiresUserAction)]) { + self.webView.mediaPlaybackRequiresUserAction = NO; + } + + // By default, overscroll bouncing is allowed. + // UIWebViewBounce has been renamed to DisallowOverscroll, but both are checked. + BOOL bounceAllowed = YES; + NSNumber* disallowOverscroll = [self settingForKey:@"DisallowOverscroll"]; + if (disallowOverscroll == nil) { + NSNumber* bouncePreference = [self settingForKey:@"UIWebViewBounce"]; + bounceAllowed = (bouncePreference == nil || [bouncePreference boolValue]); + } else { + bounceAllowed = ![disallowOverscroll boolValue]; + } + + // prevent webView from bouncing + // based on the DisallowOverscroll/UIWebViewBounce key in config.xml + if (!bounceAllowed) { + if ([self.webView respondsToSelector:@selector(scrollView)]) { + ((UIScrollView*)[self.webView scrollView]).bounces = NO; + } else { + for (id subview in self.webView.subviews) { + if ([[subview class] isSubclassOfClass:[UIScrollView class]]) { + ((UIScrollView*)subview).bounces = NO; + } + } + } + } + + NSString* decelerationSetting = [self settingForKey:@"UIWebViewDecelerationSpeed"]; + if (![@"fast" isEqualToString:decelerationSetting]) { + [self.webView.scrollView setDecelerationRate:UIScrollViewDecelerationRateNormal]; + } + + /* + * iOS 6.0 UIWebView properties + */ + if (IsAtLeastiOSVersion(@"6.0")) { + BOOL keyboardDisplayRequiresUserAction = YES; // KeyboardDisplayRequiresUserAction - defaults to YES + if ([self settingForKey:@"KeyboardDisplayRequiresUserAction"] != nil) { + if ([self settingForKey:@"KeyboardDisplayRequiresUserAction"]) { + keyboardDisplayRequiresUserAction = [(NSNumber*)[self settingForKey:@"KeyboardDisplayRequiresUserAction"] boolValue]; + } + } + + // property check for compiling under iOS < 6 + if ([self.webView respondsToSelector:@selector(setKeyboardDisplayRequiresUserAction:)]) { + [self.webView setValue:[NSNumber numberWithBool:keyboardDisplayRequiresUserAction] forKey:@"keyboardDisplayRequiresUserAction"]; + } + + BOOL suppressesIncrementalRendering = NO; // SuppressesIncrementalRendering - defaults to NO + if ([self settingForKey:@"SuppressesIncrementalRendering"] != nil) { + if ([self settingForKey:@"SuppressesIncrementalRendering"]) { + suppressesIncrementalRendering = [(NSNumber*)[self settingForKey:@"SuppressesIncrementalRendering"] boolValue]; + } + } + + // property check for compiling under iOS < 6 + if ([self.webView respondsToSelector:@selector(setSuppressesIncrementalRendering:)]) { + [self.webView setValue:[NSNumber numberWithBool:suppressesIncrementalRendering] forKey:@"suppressesIncrementalRendering"]; + } + } + + /* + * iOS 7.0 UIWebView properties + */ + if (IsAtLeastiOSVersion(@"7.0")) { + SEL ios7sel = nil; + id prefObj = nil; + + CGFloat gapBetweenPages = 0.0; // default + prefObj = [self settingForKey:@"GapBetweenPages"]; + if (prefObj != nil) { + gapBetweenPages = [prefObj floatValue]; + } + + // property check for compiling under iOS < 7 + ios7sel = NSSelectorFromString(@"setGapBetweenPages:"); + if ([self.webView respondsToSelector:ios7sel]) { + [self.webView setValue:[NSNumber numberWithFloat:gapBetweenPages] forKey:@"gapBetweenPages"]; + } + + CGFloat pageLength = 0.0; // default + prefObj = [self settingForKey:@"PageLength"]; + if (prefObj != nil) { + pageLength = [[self settingForKey:@"PageLength"] floatValue]; + } + + // property check for compiling under iOS < 7 + ios7sel = NSSelectorFromString(@"setPageLength:"); + if ([self.webView respondsToSelector:ios7sel]) { + [self.webView setValue:[NSNumber numberWithBool:pageLength] forKey:@"pageLength"]; + } + + NSInteger paginationBreakingMode = 0; // default - UIWebPaginationBreakingModePage + prefObj = [self settingForKey:@"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; + } + } + + // property check for compiling under iOS < 7 + ios7sel = NSSelectorFromString(@"setPaginationBreakingMode:"); + if ([self.webView respondsToSelector:ios7sel]) { + [self.webView setValue:[NSNumber numberWithInteger:paginationBreakingMode] forKey:@"paginationBreakingMode"]; + } + + NSInteger paginationMode = 0; // default - UIWebPaginationModeUnpaginated + prefObj = [self settingForKey:@"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; + } + } + + // property check for compiling under iOS < 7 + ios7sel = NSSelectorFromString(@"setPaginationMode:"); + if ([self.webView respondsToSelector:ios7sel]) { + [self.webView setValue:[NSNumber numberWithInteger:paginationMode] forKey:@"paginationMode"]; + } + } + + 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"]; + } + + [self registerPlugin:[[CDVHandleOpenURL alloc] initWithWebView:self.webView] withClassName:NSStringFromClass([CDVHandleOpenURL class])]; + + // ///////////////// + NSURL* appURL = [self appUrl]; + + [CDVUserAgentUtil acquireLock:^(NSInteger lockToken) { + _userAgentLockToken = lockToken; + [CDVUserAgentUtil setUserAgent:self.userAgent lockToken:lockToken]; + if (appURL) { + NSURLRequest* appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0]; + [self.webView 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 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] relativeToURL:errorUrl]; + NSLog(@"%@", [errorUrl absoluteString]); + [self.webView loadRequest:[NSURLRequest requestWithURL:errorUrl]]; + } else { + NSString* html = [NSString stringWithFormat:@"<html><body> %@ </body></html>", loadErr]; + [self.webView loadHTMLString:html baseURL:nil]; + } + } + }]; +} + +- (id)settingForKey:(NSString*)key +{ + return [[self settings] objectForKey:[key lowercaseString]]; +} + +- (void)setSetting:(id)setting forKey:(NSString*)key +{ + [[self settings] setObject:setting forKey:[key lowercaseString]]; +} + +- (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; +} + +- (NSInteger)mapIosOrientationToJsOrientation:(UIInterfaceOrientation)orientation +{ + switch (orientation) { + case UIInterfaceOrientationPortraitUpsideDown: + return 180; + + case UIInterfaceOrientationLandscapeLeft: + return -90; + + case UIInterfaceOrientationLandscapeRight: + return 90; + + case UIInterfaceOrientationPortrait: + return 0; + + default: + return 0; + } +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation +{ + // First, ask the webview via JS if it supports the new orientation + NSString* jsCall = [NSString stringWithFormat: + @"window.shouldRotateToOrientation && window.shouldRotateToOrientation(%ld);" + , (long)[self mapIosOrientationToJsOrientation:interfaceOrientation]]; + NSString* res = [webView stringByEvaluatingJavaScriptFromString:jsCall]; + + if ([res length] > 0) { + return [res boolValue]; + } + + // if js did not handle the new orientation (no return value), use values from the plist (via supportedOrientations) + return [self supportsOrientation:interfaceOrientation]; +} + +- (BOOL)shouldAutorotate +{ + return YES; +} + +- (NSUInteger)supportedInterfaceOrientations +{ + NSUInteger ret = 0; + + if ([self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationPortrait]) { + ret = ret | (1 << UIInterfaceOrientationPortrait); + } + if ([self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationPortraitUpsideDown]) { + ret = ret | (1 << UIInterfaceOrientationPortraitUpsideDown); + } + if ([self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationLandscapeRight]) { + ret = ret | (1 << UIInterfaceOrientationLandscapeRight); + } + if ([self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationLandscapeLeft]) { + ret = ret | (1 << UIInterfaceOrientationLandscapeLeft); + } + + return ret; +} + +- (BOOL)supportsOrientation:(UIInterfaceOrientation)orientation +{ + return [self.supportedOrientations containsObject:[NSNumber numberWithInt:orientation]]; +} + +- (UIWebView*)newCordovaViewWithFrame:(CGRect)bounds +{ + return [[UIWebView alloc] initWithFrame:bounds]; +} + +- (NSString*)userAgent +{ + if (_userAgent == nil) { + NSString* localBaseUserAgent; + if (self.baseUserAgent != nil) { + localBaseUserAgent = self.baseUserAgent; + } else { + localBaseUserAgent = [CDVUserAgentUtil originalUserAgent]; + } + // Use our address as a unique number to append to the User-Agent. + _userAgent = [NSString stringWithFormat:@"%@ (%lld)", localBaseUserAgent, (long long)self]; + } + return _userAgent; +} + +- (void)createGapView +{ + CGRect webViewBounds = self.view.bounds; + + webViewBounds.origin = self.view.bounds.origin; + + self.webView = [self newCordovaViewWithFrame:webViewBounds]; + self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); + + [self.view addSubview:self.webView]; + [self.view sendSubviewToBack:self.webView]; +} + +- (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. +} + +- (void)viewDidUnload +{ + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; + + self.webView.delegate = nil; + self.webView = nil; + [CDVUserAgentUtil releaseLock:&_userAgentLockToken]; + + [super viewDidUnload]; +} + +#pragma mark UIWebViewDelegate + +/** + 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."); + [_commandQueue resetRequestId]; + [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginResetNotification object:self.webView]]; +} + +/** + Called when the webview finishes loading. This stops the activity view. + */ +- (void)webViewDidFinishLoad:(UIWebView*)theWebView +{ + NSLog(@"Finished load of: %@", theWebView.request.URL); + // It's safe to release the lock even if this is just a sub-frame that's finished loading. + [CDVUserAgentUtil releaseLock:&_userAgentLockToken]; + + /* + * Hide the Top Activity THROBBER in the Battery Bar + */ + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; + + [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPageDidLoadNotification object:self.webView]]; +} + +- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error +{ + [CDVUserAgentUtil releaseLock:&_userAgentLockToken]; + + NSString* message = [NSString stringWithFormat:@"Failed to load webpage with error: %@", [error localizedDescription]]; + NSLog(@"%@", message); + + NSURL* errorUrl = [self errorUrl]; + if (errorUrl) { + errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [message stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] relativeToURL:errorUrl]; + NSLog(@"%@", [errorUrl absoluteString]); + [theWebView loadRequest:[NSURLRequest requestWithURL:errorUrl]]; + } +} + +- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType +{ + NSURL* url = [request URL]; + + /* + * 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"]) { + [_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. + [_commandQueue executePending]; + return NO; + } + + if ([[url fragment] hasPrefix:@"%01"] || [[url fragment] hasPrefix:@"%02"]) { + // Delegate is called *immediately* for hash changes. This means that any + // calls to stringByEvaluatingJavascriptFromString will occur in the middle + // of an existing (paused) call stack. This doesn't cause errors, but may + // be unexpected to callers (exec callbacks will be called before exec() even + // returns). To avoid this, we do not do any synchronous JS evals by using + // flushCommandQueueWithDelayedJs. + NSString* inlineCommands = [[url fragment] substringFromIndex:3]; + if ([inlineCommands length] == 0) { + // Reach in right away since the WebCore / Main thread are already synchronized. + [_commandQueue fetchCommandsFromJs]; + } else { + inlineCommands = [inlineCommands stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [_commandQueue enqueueCommandBatch:inlineCommands]; + } + // Switch these for minor performance improvements, and to really live on the wild side. + // Callbacks will occur in the middle of the location.hash = ... statement! + [(CDVCommandDelegateImpl*)_commandDelegate flushCommandQueueWithDelayedJs]; + // [_commandQueue executePending]; + + // Although we return NO, the hash change does end up taking effect. + return NO; + } + + /* + * Give plugins the chance to handle the url + */ + for (NSString* pluginName in pluginObjects) { + CDVPlugin* plugin = [pluginObjects objectForKey:pluginName]; + SEL selector = NSSelectorFromString(@"shouldOverrideLoadWithRequest:navigationType:"); + if ([plugin respondsToSelector:selector]) { + if (((BOOL (*)(id, SEL, id, int))objc_msgSend)(plugin, selector, request, navigationType) == YES) { + return NO; + } + } + } + + /* + * If a URL is being loaded that's a file/http/https URL, just load it internally + */ + if ([url isFileURL]) { + return YES; + } + + /* + * If we loaded the HTML from a string, we let the app handle it + */ + else if (self.loadFromString == YES) { + self.loadFromString = NO; + return YES; + } + + /* + * all tel: scheme urls we let the UIWebview handle it using the default behavior + */ + else if ([[url scheme] isEqualToString:@"tel"]) { + return YES; + } + + /* + * all about: scheme urls are not handled + */ + else if ([[url scheme] isEqualToString:@"about"]) { + return NO; + } + + /* + * all data: scheme urls are handled + */ + else if ([[url scheme] isEqualToString:@"data"]) { + return YES; + } + + /* + * Handle all other types of urls (tel:, sms:), and requests to load a url in the main webview. + */ + else { + if ([self.whitelist schemeIsAllowed:[url scheme]]) { + return [self.whitelist URLIsAllowed:url]; + } else { + if ([[UIApplication sharedApplication] canOpenURL:url]) { + [[UIApplication sharedApplication] openURL:url]; + } else { // handle any custom schemes to plugins + [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]]; + } + } + + return NO; + } + + return YES; +} + +#pragma mark GapHelpers + +- (void)javascriptAlert:(NSString*)text +{ + NSString* jsString = [NSString stringWithFormat:@"alert('%@');", text]; + + [self.commandDelegate evalJs:jsString]; +} + ++ (NSString*)applicationDocumentsDirectory +{ + NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString* basePath = (([paths count] > 0) ? ([paths objectAtIndex : 0]) : nil); + + return basePath; +} + +#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] initWithWebView:webView]; + + 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; +} + +/** + Returns the contents of the named plist bundle, loaded as a dictionary object + */ ++ (NSDictionary*)getBundlePlist:(NSString*)plistName +{ + NSString* errorDesc = nil; + NSPropertyListFormat format; + NSString* plistPath = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"]; + NSData* plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; + NSDictionary* temp = (NSDictionary*)[NSPropertyListSerialization + propertyListFromData:plistXML + mutabilityOption:NSPropertyListMutableContainersAndLeaves + format:&format errorDescription:&errorDesc]; + + return temp; +} + +#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); + } + } +} + +/* + 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 +{ + // 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 +{ + // NSLog(@"%@",@"applicationWillEnterForeground"); + [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('resume');"]; +} + +// This method is called to let your application know that it moved from the inactive to active state. +- (void)onAppDidBecomeActive:(NSNotification*)notification +{ + // 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 +{ + // NSLog(@"%@",@"applicationDidEnterBackground"); + [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('pause', null, true);" scheduledOnRunLoop:NO]; +} + +// /////////////////////// + +- (void)onPageDidLoad:(NSNotification*)notification +{ + if (self.openURL) { + [self processOpenUrl:self.openURL pageLoaded:YES]; + self.openURL = nil; + } +} + +- (void)processOpenUrl:(NSURL*)url pageLoaded:(BOOL)pageLoaded +{ + if (!pageLoaded) { + // query the webview for readystate + NSString* readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"]; + pageLoaded = [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"]; + } + + if (pageLoaded) { + // calls into javascript global function 'handleOpenURL' + NSString* jsString = [NSString stringWithFormat:@"if (typeof handleOpenURL === 'function') { handleOpenURL(\"%@\");}", url]; + [self.webView stringByEvaluatingJavaScriptFromString:jsString]; + } else { + // save for when page has loaded + self.openURL = url; + } +} + +- (void)processOpenUrl:(NSURL*)url +{ + [self processOpenUrl:url pageLoaded:NO]; +} + +// /////////////////////// + +- (void)dealloc +{ + [CDVURLProtocol unregisterViewController:self]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + self.webView.delegate = nil; + self.webView = nil; + [CDVUserAgentUtil releaseLock:&_userAgentLockToken]; + [_commandQueue dispose]; + [[self.pluginObjects allValues] makeObjectsPerformSelector:@selector(dispose)]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWebViewDelegate.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWebViewDelegate.h new file mode 100644 index 00000000..f6c419f7 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWebViewDelegate.h @@ -0,0 +1,41 @@ +/* + 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 "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 CDVWebViewDelegate : 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 diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWebViewDelegate.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWebViewDelegate.m new file mode 100644 index 00000000..514827e5 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWebViewDelegate.m @@ -0,0 +1,412 @@ +/* + 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. +// + +#import "CDVWebViewDelegate.h" +#import "CDVAvailability.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 CDVWebViewDelegate + +- (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]; + + if ([scheme isEqualToString:@"mailto"] || [scheme isEqualToString:@"tel"]) { + return YES; + } + + 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: + { + _loadCount = 0; + _state = STATE_WAITING_FOR_LOAD_START; + NSString* description = [NSString stringWithFormat:@"CDVWebViewDelegate: Navigation started when state=%ld", (long)_state]; + NSLog(@"%@", description); + if ([_delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) { + NSDictionary* errorDictionary = @{NSLocalizedDescriptionKey : description}; + NSError* error = [[NSError alloc] initWithDomain:@"CDVWebViewDelegate" code:1 userInfo:errorDictionary]; + [_delegate 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: + if (IsAtLeastiOSVersion(@"6.0")) { + break; + } + // If history.go(-1) is used pre-iOS6, the shouldStartLoadWithRequest function is not called. + // Without shouldLoad, we can't distinguish an iframe from a top-level navigation. + // We could try to distinguish using [UIWebView canGoForward], but that's too much complexity, + // and would work only on the first time it was used. + + // Our work-around is to set a JS variable and poll until it disappears (from a navigation). + _state = STATE_IOS5_POLLING_FOR_LOAD_START; + _loadStartPollCount = 0; + [self setLoadToken:webView]; + [self pollForPageLoadStart:webView]; + 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: + 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 diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWhitelist.h b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWhitelist.h new file mode 100644 index 00000000..91650970 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWhitelist.m b/StoneIsland/platforms/ios/CordovaLib/Classes/CDVWhitelist.m new file mode 100644 index 00000000..8e3be752 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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; + } 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 || [_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] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; + // 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]]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSArray+Comparisons.h b/StoneIsland/platforms/ios/CordovaLib/Classes/NSArray+Comparisons.h new file mode 100644 index 00000000..7dd68290 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/NSArray+Comparisons.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 "CDVAvailabilityDeprecated.h" + +@interface NSArray (Comparisons) + +- (id)objectAtIndex:(NSUInteger)index withDefault:(id)aDefault CDV_DEPRECATED(3.8 .0, "Use [command argumentAtIndex] instead."); + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSArray+Comparisons.m b/StoneIsland/platforms/ios/CordovaLib/Classes/NSArray+Comparisons.m new file mode 100644 index 00000000..e29c03da --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/NSArray+Comparisons.m @@ -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. + */ + +#import "NSArray+Comparisons.h" + +@implementation NSArray (Comparisons) + +- (id)objectAtIndex:(NSUInteger)index withDefault:(id)aDefault +{ + id obj = nil; + + @try { + if (index < [self count]) { + obj = [self objectAtIndex:index]; + } + if ((obj == [NSNull null]) || (obj == nil)) { + return aDefault; + } + } + @catch(NSException* exception) { + NSLog(@"Exception - Name: %@ Reason: %@", [exception name], [exception reason]); + } + + return obj; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSData+Base64.h b/StoneIsland/platforms/ios/CordovaLib/Classes/NSData+Base64.h new file mode 100644 index 00000000..c92d1f6a --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/NSData+Base64.h @@ -0,0 +1,47 @@ +// +// NSData+Base64.h +// base64 +// +// Created by Matt Gallagher on 2009/06/03. +// Copyright 2009 Matt Gallagher. All rights reserved. +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. Permission is granted to anyone to +// use this software for any purpose, including commercial applications, and to +// alter it and redistribute it freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source +// distribution. +// + +#import <Foundation/Foundation.h> +#import "CDVAvailabilityDeprecated.h" + +void *CDVNewBase64Decode( + const char* inputBuffer, + size_t length, + size_t * outputLength); + +char *CDVNewBase64Encode( + const void* inputBuffer, + size_t length, + bool separateLines, + size_t * outputLength); + +@interface NSData (CDVBase64) + ++ (NSData*)dataFromBase64String:(NSString*)aString CDV_DEPRECATED(3.8 .0, "Use cdv_dataFromBase64String"); + +- (NSString*)base64EncodedString CDV_DEPRECATED(3.8 .0, "Use [NSData cdv_base64EncodedString]"); + ++ (NSData*)cdv_dataFromBase64String:(NSString*)aString; +- (NSString*)cdv_base64EncodedString; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSData+Base64.m b/StoneIsland/platforms/ios/CordovaLib/Classes/NSData+Base64.m new file mode 100644 index 00000000..634dff67 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/NSData+Base64.m @@ -0,0 +1,308 @@ +// +// NSData+Base64.m +// base64 +// +// Created by Matt Gallagher on 2009/06/03. +// Copyright 2009 Matt Gallagher. All rights reserved. +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. Permission is granted to anyone to +// use this software for any purpose, including commercial applications, and to +// alter it and redistribute it freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source +// distribution. +// + +#import "NSData+Base64.h" + +// +// Mapping from 6 bit pattern to ASCII character. +// +static unsigned char base64EncodeLookup[65] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// +// Definition for "masked-out" areas of the base64DecodeLookup mapping +// +#define xx 65 + +// +// Mapping from ASCII character to 6 bit pattern. +// +static unsigned char base64DecodeLookup[256] = +{ + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, 62, xx, xx, xx, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, xx, xx, xx, xx, xx, xx, + xx, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, xx, xx, xx, xx, xx, + xx, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, +}; + +// +// Fundamental sizes of the binary and base64 encode/decode units in bytes +// +#define BINARY_UNIT_SIZE 3 +#define BASE64_UNIT_SIZE 4 + +// +// NewBase64Decode +// +// Decodes the base64 ASCII string in the inputBuffer to a newly malloced +// output buffer. +// +// inputBuffer - the source ASCII string for the decode +// length - the length of the string or -1 (to specify strlen should be used) +// outputLength - if not-NULL, on output will contain the decoded length +// +// returns the decoded buffer. Must be free'd by caller. Length is given by +// outputLength. +// +void *CDVNewBase64Decode( + const char* inputBuffer, + size_t length, + size_t * outputLength) +{ + if (length == -1) { + length = strlen(inputBuffer); + } + + size_t outputBufferSize = + ((length + BASE64_UNIT_SIZE - 1) / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE; + unsigned char* outputBuffer = (unsigned char*)malloc(outputBufferSize); + + size_t i = 0; + size_t j = 0; + + while (i < length) { + // + // Accumulate 4 valid characters (ignore everything else) + // + unsigned char accumulated[BASE64_UNIT_SIZE]; + size_t accumulateIndex = 0; + + while (i < length) { + unsigned char decode = base64DecodeLookup[inputBuffer[i++]]; + if (decode != xx) { + accumulated[accumulateIndex] = decode; + accumulateIndex++; + + if (accumulateIndex == BASE64_UNIT_SIZE) { + break; + } + } + } + + // + // Store the 6 bits from each of the 4 characters as 3 bytes + // + // (Uses improved bounds checking suggested by Alexandre Colucci) + // + if (accumulateIndex >= 2) { + outputBuffer[j] = (accumulated[0] << 2) | (accumulated[1] >> 4); + } + if (accumulateIndex >= 3) { + outputBuffer[j + 1] = (accumulated[1] << 4) | (accumulated[2] >> 2); + } + if (accumulateIndex >= 4) { + outputBuffer[j + 2] = (accumulated[2] << 6) | accumulated[3]; + } + j += accumulateIndex - 1; + } + + if (outputLength) { + *outputLength = j; + } + return outputBuffer; +} + +// +// NewBase64Encode +// +// Encodes the arbitrary data in the inputBuffer as base64 into a newly malloced +// output buffer. +// +// inputBuffer - the source data for the encode +// length - the length of the input in bytes +// separateLines - if zero, no CR/LF characters will be added. Otherwise +// a CR/LF pair will be added every 64 encoded chars. +// outputLength - if not-NULL, on output will contain the encoded length +// (not including terminating 0 char) +// +// returns the encoded buffer. Must be free'd by caller. Length is given by +// outputLength. +// +char *CDVNewBase64Encode( + const void* buffer, + size_t length, + bool separateLines, + size_t * outputLength) +{ + const unsigned char* inputBuffer = (const unsigned char*)buffer; + +#define MAX_NUM_PADDING_CHARS 2 +#define OUTPUT_LINE_LENGTH 64 +#define INPUT_LINE_LENGTH ((OUTPUT_LINE_LENGTH / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE) +#define CR_LF_SIZE 2 + + // + // Byte accurate calculation of final buffer size + // + size_t outputBufferSize = + ((length / BINARY_UNIT_SIZE) + + ((length % BINARY_UNIT_SIZE) ? 1 : 0)) + * BASE64_UNIT_SIZE; + if (separateLines) { + outputBufferSize += + (outputBufferSize / OUTPUT_LINE_LENGTH) * CR_LF_SIZE; + } + + // + // Include space for a terminating zero + // + outputBufferSize += 1; + + // + // Allocate the output buffer + // + char* outputBuffer = (char*)malloc(outputBufferSize); + if (!outputBuffer) { + return NULL; + } + + size_t i = 0; + size_t j = 0; + const size_t lineLength = separateLines ? INPUT_LINE_LENGTH : length; + size_t lineEnd = lineLength; + + while (true) { + if (lineEnd > length) { + lineEnd = length; + } + + for (; i + BINARY_UNIT_SIZE - 1 < lineEnd; i += BINARY_UNIT_SIZE) { + // + // Inner loop: turn 48 bytes into 64 base64 characters + // + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4) + | ((inputBuffer[i + 1] & 0xF0) >> 4)]; + outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i + 1] & 0x0F) << 2) + | ((inputBuffer[i + 2] & 0xC0) >> 6)]; + outputBuffer[j++] = base64EncodeLookup[inputBuffer[i + 2] & 0x3F]; + } + + if (lineEnd == length) { + break; + } + + // + // Add the newline + // + // outputBuffer[j++] = '\r'; + // outputBuffer[j++] = '\n'; + lineEnd += lineLength; + } + + if (i + 1 < length) { + // + // Handle the single '=' case + // + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4) + | ((inputBuffer[i + 1] & 0xF0) >> 4)]; + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i + 1] & 0x0F) << 2]; + outputBuffer[j++] = '='; + } else if (i < length) { + // + // Handle the double '=' case + // + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0x03) << 4]; + outputBuffer[j++] = '='; + outputBuffer[j++] = '='; + } + outputBuffer[j] = 0; + + // + // Set the output length and return the buffer + // + if (outputLength) { + *outputLength = j; + } + return outputBuffer; +} + +@implementation NSData (CDVBase64) + +// +// dataFromBase64String: +// +// Creates an NSData object containing the base64 decoded representation of +// the base64 string 'aString' +// +// Parameters: +// aString - the base64 string to decode +// +// returns the autoreleased NSData representation of the base64 string +// ++ (NSData*)cdv_dataFromBase64String:(NSString*)aString +{ + size_t outputLength = 0; + void* outputBuffer = CDVNewBase64Decode([aString UTF8String], [aString length], &outputLength); + + return [NSData dataWithBytesNoCopy:outputBuffer length:outputLength freeWhenDone:YES]; +} + +// +// base64EncodedString +// +// Creates an NSString object that contains the base 64 encoding of the +// receiver's data. Lines are broken at 64 characters long. +// +// returns an autoreleased NSString being the base 64 representation of the +// receiver. +// +- (NSString*)cdv_base64EncodedString +{ + size_t outputLength = 0; + char* outputBuffer = + CDVNewBase64Encode([self bytes], [self length], true, &outputLength); + + NSString* result = [[NSString alloc] initWithBytesNoCopy:outputBuffer + length:outputLength + encoding:NSASCIIStringEncoding + freeWhenDone:YES]; + + return result; +} + ++ (NSData*)dataFromBase64String:(NSString*)aString +{ + return [self cdv_dataFromBase64String:aString]; +} + +- (NSString*)base64EncodedString +{ + return [self cdv_base64EncodedString]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSDictionary+Extensions.h b/StoneIsland/platforms/ios/CordovaLib/Classes/NSDictionary+Extensions.h new file mode 100644 index 00000000..4020864e --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/NSDictionary+Extensions.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. + */ + +#import <Foundation/Foundation.h> +#import "CDVAvailabilityDeprecated.h" + +@interface NSDictionary (org_apache_cordova_NSDictionary_Extension) + +- (bool)existsValue:(NSString*)expectedValue forKey:(NSString*)key CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (NSInteger)integerValueForKey:(NSString*)key defaultValue:(NSInteger)defaultValue withRange:(NSRange)range CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (NSInteger)integerValueForKey:(NSString*)key defaultValue:(NSInteger)defaultValue CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (BOOL)typeValueForKey:(NSString*)key isArray:(BOOL*)bArray isNull:(BOOL*)bNull isNumber:(BOOL*)bNumber isString:(BOOL*)bString CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (BOOL)valueForKeyIsArray:(NSString*)key CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (BOOL)valueForKeyIsNull:(NSString*)key CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (BOOL)valueForKeyIsString:(NSString*)key CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (BOOL)valueForKeyIsNumber:(NSString*)key CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +- (NSDictionary*)dictionaryWithLowercaseKeys CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSDictionary+Extensions.m b/StoneIsland/platforms/ios/CordovaLib/Classes/NSDictionary+Extensions.m new file mode 100644 index 00000000..0361ff95 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/NSDictionary+Extensions.m @@ -0,0 +1,159 @@ +/* + 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+Extensions.h" +#import <math.h> + +@implementation NSDictionary (org_apache_cordova_NSDictionary_Extension) + +- (bool)existsValue:(NSString*)expectedValue forKey:(NSString*)key +{ + id val = [self valueForKey:key]; + bool exists = false; + + if (val != nil) { + exists = [(NSString*)val compare : expectedValue options : NSCaseInsensitiveSearch] == 0; + } + + return exists; +} + +- (NSInteger)integerValueForKey:(NSString*)key defaultValue:(NSInteger)defaultValue withRange:(NSRange)range +{ + NSInteger value = defaultValue; + + NSNumber* val = [self valueForKey:key]; // value is an NSNumber + + if (val != nil) { + value = [val integerValue]; + } + + // min, max checks + value = MAX(range.location, value); + value = MIN(range.length, value); + + return value; +} + +- (NSInteger)integerValueForKey:(NSString*)key defaultValue:(NSInteger)defaultValue +{ + NSInteger value = defaultValue; + + NSNumber* val = [self valueForKey:key]; // value is an NSNumber + + if (val != nil) { + value = [val integerValue]; + } + return value; +} + +/* + * Determine the type of object stored in a dictionary + * IN: + * (BOOL*) bString - if exists will be set to YES if object is an NSString, NO if not + * (BOOL*) bNull - if exists will be set to YES if object is an NSNull, NO if not + * (BOOL*) bArray - if exists will be set to YES if object is an NSArray, NO if not + * (BOOL*) bNumber - if exists will be set to YES if object is an NSNumber, NO if not + * + * OUT: + * YES if key exists + * NO if key does not exist. Input parameters remain untouched + * + */ + +- (BOOL)typeValueForKey:(NSString*)key isArray:(BOOL*)bArray isNull:(BOOL*)bNull isNumber:(BOOL*)bNumber isString:(BOOL*)bString +{ + BOOL bExists = YES; + NSObject* value = [self objectForKey:key]; + + if (value) { + bExists = YES; + if (bString) { + *bString = [value isKindOfClass:[NSString class]]; + } + if (bNull) { + *bNull = [value isKindOfClass:[NSNull class]]; + } + if (bArray) { + *bArray = [value isKindOfClass:[NSArray class]]; + } + if (bNumber) { + *bNumber = [value isKindOfClass:[NSNumber class]]; + } + } + return bExists; +} + +- (BOOL)valueForKeyIsArray:(NSString*)key +{ + BOOL bArray = NO; + NSObject* value = [self objectForKey:key]; + + if (value) { + bArray = [value isKindOfClass:[NSArray class]]; + } + return bArray; +} + +- (BOOL)valueForKeyIsNull:(NSString*)key +{ + BOOL bNull = NO; + NSObject* value = [self objectForKey:key]; + + if (value) { + bNull = [value isKindOfClass:[NSNull class]]; + } + return bNull; +} + +- (BOOL)valueForKeyIsString:(NSString*)key +{ + BOOL bString = NO; + NSObject* value = [self objectForKey:key]; + + if (value) { + bString = [value isKindOfClass:[NSString class]]; + } + return bString; +} + +- (BOOL)valueForKeyIsNumber:(NSString*)key +{ + BOOL bNumber = NO; + NSObject* value = [self objectForKey:key]; + + if (value) { + bNumber = [value isKindOfClass:[NSNumber class]]; + } + return bNumber; +} + +- (NSDictionary*)dictionaryWithLowercaseKeys +{ + NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:self.count]; + NSString* key; + + for (key in self) { + [result setObject:[self objectForKey:key] forKey:[key lowercaseString]]; + } + + return result; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSMutableArray+QueueAdditions.h b/StoneIsland/platforms/ios/CordovaLib/Classes/NSMutableArray+QueueAdditions.h new file mode 100644 index 00000000..31940949 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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)pop; +- (id)queueHead; +- (id)dequeue; +- (void)enqueue:(id)obj; + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/NSMutableArray+QueueAdditions.m b/StoneIsland/platforms/ios/CordovaLib/Classes/NSMutableArray+QueueAdditions.m new file mode 100644 index 00000000..9e67edeb --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/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)queueHead +{ + if ([self count] == 0) { + return nil; + } + + return [self objectAtIndex:0]; +} + +- (__autoreleasing id)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)pop +{ + return [self dequeue]; +} + +- (void)enqueue:(id)object +{ + [self addObject:object]; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/UIDevice+Extensions.h b/StoneIsland/platforms/ios/CordovaLib/Classes/UIDevice+Extensions.h new file mode 100644 index 00000000..1b2c0739 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/UIDevice+Extensions.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 <Foundation/Foundation.h> +#import "CDVAvailabilityDeprecated.h" + +@interface UIDevice (org_apache_cordova_UIDevice_Extension) + +/* + Get the unique identifier from the app bundle's folder, which is already a GUID + Upgrading and/or deleting the app and re-installing will get you a new GUID, so + this is only unique per install per device. + */ +- (NSString*)uniqueAppInstanceIdentifier CDV_DEPRECATED(3.8 .0, "API is slated for removal in 4.0.0"); + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/Classes/UIDevice+Extensions.m b/StoneIsland/platforms/ios/CordovaLib/Classes/UIDevice+Extensions.m new file mode 100644 index 00000000..c0c91af2 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/Classes/UIDevice+Extensions.m @@ -0,0 +1,47 @@ +/* + 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 "UIDevice+Extensions.h" + +@implementation UIDevice (org_apache_cordova_UIDevice_Extension) + +- (NSString*)uniqueAppInstanceIdentifier +{ + NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; + static NSString* UUID_KEY = @"CDVUUID"; + + NSString* app_uuid = [userDefaults stringForKey:UUID_KEY]; + + if (app_uuid == nil) { + CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); + CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); + + app_uuid = [NSString stringWithString:(__bridge NSString*)uuidString]; + [userDefaults setObject:app_uuid forKey:UUID_KEY]; + [userDefaults synchronize]; + + CFRelease(uuidString); + CFRelease(uuidRef); + } + + return app_uuid; +} + +@end diff --git a/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj b/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj new file mode 100644 index 00000000..c6b0f234 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj @@ -0,0 +1,507 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1B701028177A61CF00AE11F4 /* CDVShared.h in Headers */ = {isa = PBXBuildFile; fileRef = 1B701026177A61CF00AE11F4 /* CDVShared.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1F92F4A01314023E0046367C /* CDVPluginResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F92F49E1314023E0046367C /* CDVPluginResult.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1F92F4A11314023E0046367C /* CDVPluginResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 1F92F49F1314023E0046367C /* CDVPluginResult.m */; }; + 301F2F2A14F3C9CA003FE9FC /* CDV.h in Headers */ = {isa = PBXBuildFile; fileRef = 301F2F2914F3C9CA003FE9FC /* CDV.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 302965BC13A94E9D007046C5 /* CDVDebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 302965BB13A94E9D007046C5 /* CDVDebug.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3034979C1513D56A0090E688 /* CDVLocalStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 3034979A1513D56A0090E688 /* CDVLocalStorage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3034979E1513D56A0090E688 /* CDVLocalStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 3034979B1513D56A0090E688 /* CDVLocalStorage.m */; }; + 30392E4E14F4FCAB00B9E0B8 /* CDVAvailability.h in Headers */ = {isa = PBXBuildFile; fileRef = 30392E4D14F4FCAB00B9E0B8 /* CDVAvailability.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3062D120151D0EDB000D9128 /* UIDevice+Extensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 3062D11E151D0EDB000D9128 /* UIDevice+Extensions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3062D122151D0EDB000D9128 /* UIDevice+Extensions.m in Sources */ = {isa = PBXBuildFile; fileRef = 3062D11F151D0EDB000D9128 /* UIDevice+Extensions.m */; }; + 3073E9ED1656D51200957977 /* CDVScreenOrientationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 3073E9EC1656D51200957977 /* CDVScreenOrientationDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30C684801406CB38004C1A8E /* CDVWhitelist.h in Headers */ = {isa = PBXBuildFile; fileRef = 30C6847E1406CB38004C1A8E /* CDVWhitelist.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30C684821406CB38004C1A8E /* CDVWhitelist.m in Sources */ = {isa = PBXBuildFile; fileRef = 30C6847F1406CB38004C1A8E /* CDVWhitelist.m */; }; + 30C684941407044B004C1A8E /* CDVURLProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 30C684921407044A004C1A8E /* CDVURLProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30C684961407044B004C1A8E /* CDVURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 30C684931407044A004C1A8E /* CDVURLProtocol.m */; }; + 30E33AF213A7E24B00594D64 /* CDVPlugin.h in Headers */ = {isa = PBXBuildFile; fileRef = 30E33AF013A7E24B00594D64 /* CDVPlugin.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30E33AF313A7E24B00594D64 /* CDVPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = 30E33AF113A7E24B00594D64 /* CDVPlugin.m */; }; + 30E563CF13E217EC00C949AA /* NSMutableArray+QueueAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 30E563CD13E217EC00C949AA /* NSMutableArray+QueueAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30E563D013E217EC00C949AA /* NSMutableArray+QueueAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 30E563CE13E217EC00C949AA /* NSMutableArray+QueueAdditions.m */; }; + 30E6B8CD1A8ADD900025B9EE /* CDVHandleOpenURL.h in Headers */ = {isa = PBXBuildFile; fileRef = 30E6B8CB1A8ADD900025B9EE /* CDVHandleOpenURL.h */; }; + 30E6B8CE1A8ADD900025B9EE /* CDVHandleOpenURL.m in Sources */ = {isa = PBXBuildFile; fileRef = 30E6B8CC1A8ADD900025B9EE /* CDVHandleOpenURL.m */; }; + 30F3930B169F839700B22307 /* CDVJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 30F39309169F839700B22307 /* CDVJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30F3930C169F839700B22307 /* CDVJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 30F3930A169F839700B22307 /* CDVJSON.m */; }; + 30F5EBAB14CA26E700987760 /* CDVCommandDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 30F5EBA914CA26E700987760 /* CDVCommandDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7E14B5A81705050A0032169E /* CDVTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7E14B5A61705050A0032169E /* CDVTimer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7E14B5A91705050A0032169E /* CDVTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E14B5A71705050A0032169E /* CDVTimer.m */; }; + 7E22B88519E4C0210026F95E /* CDVAvailabilityDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 7E22B88419E4C0210026F95E /* CDVAvailabilityDeprecated.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8852C43A14B65FD800F0E735 /* CDVViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 8852C43614B65FD800F0E735 /* CDVViewController.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8852C43C14B65FD800F0E735 /* CDVViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8852C43714B65FD800F0E735 /* CDVViewController.m */; }; + 8887FD681090FBE7009987E8 /* NSDictionary+Extensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 8887FD281090FBE7009987E8 /* NSDictionary+Extensions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8887FD691090FBE7009987E8 /* NSDictionary+Extensions.m in Sources */ = {isa = PBXBuildFile; fileRef = 8887FD291090FBE7009987E8 /* NSDictionary+Extensions.m */; }; + 8887FD741090FBE7009987E8 /* CDVInvokedUrlCommand.h in Headers */ = {isa = PBXBuildFile; fileRef = 8887FD341090FBE7009987E8 /* CDVInvokedUrlCommand.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8887FD751090FBE7009987E8 /* CDVInvokedUrlCommand.m in Sources */ = {isa = PBXBuildFile; fileRef = 8887FD351090FBE7009987E8 /* CDVInvokedUrlCommand.m */; }; + 8887FD8F1090FBE7009987E8 /* NSData+Base64.h in Headers */ = {isa = PBXBuildFile; fileRef = 8887FD501090FBE7009987E8 /* NSData+Base64.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8887FD901090FBE7009987E8 /* NSData+Base64.m in Sources */ = {isa = PBXBuildFile; fileRef = 8887FD511090FBE7009987E8 /* NSData+Base64.m */; }; + EB3B3547161CB44D003DBE7D /* CDVCommandQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = EB3B3545161CB44D003DBE7D /* CDVCommandQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EB3B3548161CB44D003DBE7D /* CDVCommandQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = EB3B3546161CB44D003DBE7D /* CDVCommandQueue.m */; }; + EB3B357C161F2A45003DBE7D /* CDVCommandDelegateImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = EB3B357A161F2A44003DBE7D /* CDVCommandDelegateImpl.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EB3B357D161F2A45003DBE7D /* CDVCommandDelegateImpl.m in Sources */ = {isa = PBXBuildFile; fileRef = EB3B357B161F2A45003DBE7D /* CDVCommandDelegateImpl.m */; }; + EB6A98541A77EE470013FCDB /* CDVJSON_private.m in Sources */ = {isa = PBXBuildFile; fileRef = EB6A98521A77EE470013FCDB /* CDVJSON_private.m */; }; + EB96673B16A8970A00D86CDF /* CDVUserAgentUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = EB96673916A8970900D86CDF /* CDVUserAgentUtil.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EB96673C16A8970A00D86CDF /* CDVUserAgentUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = EB96673A16A8970900D86CDF /* CDVUserAgentUtil.m */; }; + EBA3557315ABD38C00F4DE24 /* NSArray+Comparisons.h in Headers */ = {isa = PBXBuildFile; fileRef = EBA3557115ABD38C00F4DE24 /* NSArray+Comparisons.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EBA3557515ABD38C00F4DE24 /* NSArray+Comparisons.m in Sources */ = {isa = PBXBuildFile; fileRef = EBA3557215ABD38C00F4DE24 /* NSArray+Comparisons.m */; }; + EBFF4DBC16D3FE2E008F452B /* CDVWebViewDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = EBFF4DBA16D3FE2E008F452B /* CDVWebViewDelegate.m */; }; + EBFF4DBD16D3FE2E008F452B /* CDVWebViewDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = EBFF4DBB16D3FE2E008F452B /* CDVWebViewDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F858FBC6166009A8007DA594 /* CDVConfigParser.h in Headers */ = {isa = PBXBuildFile; fileRef = F858FBC4166009A8007DA594 /* CDVConfigParser.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F858FBC7166009A8007DA594 /* CDVConfigParser.m in Sources */ = {isa = PBXBuildFile; fileRef = F858FBC5166009A8007DA594 /* CDVConfigParser.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 1B701026177A61CF00AE11F4 /* CDVShared.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVShared.h; path = Classes/CDVShared.h; sourceTree = "<group>"; }; + 1F92F49E1314023E0046367C /* CDVPluginResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVPluginResult.h; path = Classes/CDVPluginResult.h; sourceTree = "<group>"; }; + 1F92F49F1314023E0046367C /* CDVPluginResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVPluginResult.m; path = Classes/CDVPluginResult.m; sourceTree = "<group>"; }; + 301F2F2914F3C9CA003FE9FC /* CDV.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDV.h; path = Classes/CDV.h; sourceTree = "<group>"; }; + 302965BB13A94E9D007046C5 /* CDVDebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVDebug.h; path = Classes/CDVDebug.h; sourceTree = "<group>"; }; + 30325A0B136B343700982B63 /* VERSION */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = VERSION; sourceTree = "<group>"; }; + 3034979A1513D56A0090E688 /* CDVLocalStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVLocalStorage.h; path = Classes/CDVLocalStorage.h; sourceTree = "<group>"; }; + 3034979B1513D56A0090E688 /* CDVLocalStorage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVLocalStorage.m; path = Classes/CDVLocalStorage.m; sourceTree = "<group>"; }; + 30392E4D14F4FCAB00B9E0B8 /* CDVAvailability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVAvailability.h; path = Classes/CDVAvailability.h; sourceTree = "<group>"; }; + 3062D11E151D0EDB000D9128 /* UIDevice+Extensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIDevice+Extensions.h"; path = "Classes/UIDevice+Extensions.h"; sourceTree = "<group>"; }; + 3062D11F151D0EDB000D9128 /* UIDevice+Extensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIDevice+Extensions.m"; path = "Classes/UIDevice+Extensions.m"; sourceTree = "<group>"; }; + 3073E9EC1656D51200957977 /* CDVScreenOrientationDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVScreenOrientationDelegate.h; path = Classes/CDVScreenOrientationDelegate.h; sourceTree = "<group>"; }; + 30C6847E1406CB38004C1A8E /* CDVWhitelist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVWhitelist.h; path = Classes/CDVWhitelist.h; sourceTree = "<group>"; }; + 30C6847F1406CB38004C1A8E /* CDVWhitelist.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVWhitelist.m; path = Classes/CDVWhitelist.m; sourceTree = "<group>"; }; + 30C684921407044A004C1A8E /* CDVURLProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVURLProtocol.h; path = Classes/CDVURLProtocol.h; sourceTree = "<group>"; }; + 30C684931407044A004C1A8E /* CDVURLProtocol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVURLProtocol.m; path = Classes/CDVURLProtocol.m; sourceTree = "<group>"; }; + 30E33AF013A7E24B00594D64 /* CDVPlugin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVPlugin.h; path = Classes/CDVPlugin.h; sourceTree = "<group>"; }; + 30E33AF113A7E24B00594D64 /* CDVPlugin.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVPlugin.m; path = Classes/CDVPlugin.m; sourceTree = "<group>"; }; + 30E563CD13E217EC00C949AA /* NSMutableArray+QueueAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSMutableArray+QueueAdditions.h"; path = "Classes/NSMutableArray+QueueAdditions.h"; sourceTree = "<group>"; }; + 30E563CE13E217EC00C949AA /* NSMutableArray+QueueAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSMutableArray+QueueAdditions.m"; path = "Classes/NSMutableArray+QueueAdditions.m"; sourceTree = "<group>"; }; + 30E6B8CB1A8ADD900025B9EE /* CDVHandleOpenURL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVHandleOpenURL.h; path = Classes/CDVHandleOpenURL.h; sourceTree = "<group>"; }; + 30E6B8CC1A8ADD900025B9EE /* CDVHandleOpenURL.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVHandleOpenURL.m; path = Classes/CDVHandleOpenURL.m; sourceTree = "<group>"; }; + 30F39309169F839700B22307 /* CDVJSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVJSON.h; path = Classes/CDVJSON.h; sourceTree = "<group>"; }; + 30F3930A169F839700B22307 /* CDVJSON.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVJSON.m; path = Classes/CDVJSON.m; sourceTree = "<group>"; }; + 30F5EBA914CA26E700987760 /* CDVCommandDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVCommandDelegate.h; path = Classes/CDVCommandDelegate.h; sourceTree = "<group>"; }; + 686357AA141002F100DF4CF2 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + 686357AC141002F100DF4CF2 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 686357AE141002F100DF4CF2 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 686357CC14100AAD00DF4CF2 /* AddressBookUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AddressBookUI.framework; path = System/Library/Frameworks/AddressBookUI.framework; sourceTree = SDKROOT; }; + 686357CE14100ADA00DF4CF2 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + 686357CF14100ADB00DF4CF2 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; + 686357D014100ADE00DF4CF2 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; }; + 686357D214100AE700DF4CF2 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = System/Library/Frameworks/MobileCoreServices.framework; sourceTree = SDKROOT; }; + 686357D414100AF200DF4CF2 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; + 686357DC14100B1600DF4CF2 /* CoreMedia.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMedia.framework; path = System/Library/Frameworks/CoreMedia.framework; sourceTree = SDKROOT; }; + 68A32D7114102E1C006B237C /* libCordova.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libCordova.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 68A32D7414103017006B237C /* AddressBook.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AddressBook.framework; path = System/Library/Frameworks/AddressBook.framework; sourceTree = SDKROOT; }; + 7E14B5A61705050A0032169E /* CDVTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVTimer.h; path = Classes/CDVTimer.h; sourceTree = "<group>"; }; + 7E14B5A71705050A0032169E /* CDVTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVTimer.m; path = Classes/CDVTimer.m; sourceTree = "<group>"; }; + 7E22B88419E4C0210026F95E /* CDVAvailabilityDeprecated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVAvailabilityDeprecated.h; path = Classes/CDVAvailabilityDeprecated.h; sourceTree = "<group>"; }; + 8220B5C316D5427E00EC3921 /* AssetsLibrary.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AssetsLibrary.framework; path = System/Library/Frameworks/AssetsLibrary.framework; sourceTree = SDKROOT; }; + 8852C43614B65FD800F0E735 /* CDVViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVViewController.h; path = Classes/CDVViewController.h; sourceTree = "<group>"; }; + 8852C43714B65FD800F0E735 /* CDVViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVViewController.m; path = Classes/CDVViewController.m; sourceTree = "<group>"; }; + 8887FD281090FBE7009987E8 /* NSDictionary+Extensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSDictionary+Extensions.h"; path = "Classes/NSDictionary+Extensions.h"; sourceTree = "<group>"; }; + 8887FD291090FBE7009987E8 /* NSDictionary+Extensions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSDictionary+Extensions.m"; path = "Classes/NSDictionary+Extensions.m"; sourceTree = "<group>"; }; + 8887FD341090FBE7009987E8 /* CDVInvokedUrlCommand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVInvokedUrlCommand.h; path = Classes/CDVInvokedUrlCommand.h; sourceTree = "<group>"; }; + 8887FD351090FBE7009987E8 /* CDVInvokedUrlCommand.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVInvokedUrlCommand.m; path = Classes/CDVInvokedUrlCommand.m; sourceTree = "<group>"; }; + 8887FD501090FBE7009987E8 /* NSData+Base64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSData+Base64.h"; path = "Classes/NSData+Base64.h"; sourceTree = "<group>"; }; + 8887FD511090FBE7009987E8 /* NSData+Base64.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSData+Base64.m"; path = "Classes/NSData+Base64.m"; sourceTree = "<group>"; }; + AA747D9E0F9514B9006C5449 /* CordovaLib_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CordovaLib_Prefix.pch; sourceTree = SOURCE_ROOT; }; + EB3B3545161CB44D003DBE7D /* CDVCommandQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVCommandQueue.h; path = Classes/CDVCommandQueue.h; sourceTree = "<group>"; }; + EB3B3546161CB44D003DBE7D /* CDVCommandQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVCommandQueue.m; path = Classes/CDVCommandQueue.m; sourceTree = "<group>"; }; + EB3B357A161F2A44003DBE7D /* CDVCommandDelegateImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVCommandDelegateImpl.h; path = Classes/CDVCommandDelegateImpl.h; sourceTree = "<group>"; }; + EB3B357B161F2A45003DBE7D /* CDVCommandDelegateImpl.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVCommandDelegateImpl.m; path = Classes/CDVCommandDelegateImpl.m; sourceTree = "<group>"; }; + EB6A98521A77EE470013FCDB /* CDVJSON_private.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVJSON_private.m; path = Classes/CDVJSON_private.m; sourceTree = "<group>"; }; + EB6A98531A77EE470013FCDB /* CDVJSON_private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVJSON_private.h; path = Classes/CDVJSON_private.h; sourceTree = "<group>"; }; + EB96673916A8970900D86CDF /* CDVUserAgentUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVUserAgentUtil.h; path = Classes/CDVUserAgentUtil.h; sourceTree = "<group>"; }; + EB96673A16A8970900D86CDF /* CDVUserAgentUtil.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVUserAgentUtil.m; path = Classes/CDVUserAgentUtil.m; sourceTree = "<group>"; }; + EBA3557115ABD38C00F4DE24 /* NSArray+Comparisons.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSArray+Comparisons.h"; path = "Classes/NSArray+Comparisons.h"; sourceTree = "<group>"; }; + EBA3557215ABD38C00F4DE24 /* NSArray+Comparisons.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSArray+Comparisons.m"; path = "Classes/NSArray+Comparisons.m"; sourceTree = "<group>"; }; + EBFF4DBA16D3FE2E008F452B /* CDVWebViewDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVWebViewDelegate.m; path = Classes/CDVWebViewDelegate.m; sourceTree = "<group>"; }; + EBFF4DBB16D3FE2E008F452B /* CDVWebViewDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVWebViewDelegate.h; path = Classes/CDVWebViewDelegate.h; sourceTree = "<group>"; }; + F858FBC4166009A8007DA594 /* CDVConfigParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVConfigParser.h; path = Classes/CDVConfigParser.h; sourceTree = "<group>"; }; + F858FBC5166009A8007DA594 /* CDVConfigParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVConfigParser.m; path = Classes/CDVConfigParser.m; sourceTree = "<group>"; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + D2AAC07C0554694100DB518D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 034768DFFF38A50411DB9C8B /* Products */ = { + isa = PBXGroup; + children = ( + 68A32D7114102E1C006B237C /* libCordova.a */, + ); + name = Products; + sourceTree = CORDOVALIB; + }; + 0867D691FE84028FC02AAC07 /* CordovaLib */ = { + isa = PBXGroup; + children = ( + 8887FD101090FB43009987E8 /* Classes */, + 32C88DFF0371C24200C91783 /* Other Sources */, + 0867D69AFE84028FC02AAC07 /* Frameworks */, + 034768DFFF38A50411DB9C8B /* Products */, + 30325A0B136B343700982B63 /* VERSION */, + ); + name = CordovaLib; + sourceTree = "<group>"; + }; + 0867D69AFE84028FC02AAC07 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 68A32D7414103017006B237C /* AddressBook.framework */, + 8220B5C316D5427E00EC3921 /* AssetsLibrary.framework */, + 686357DC14100B1600DF4CF2 /* CoreMedia.framework */, + 686357CE14100ADA00DF4CF2 /* AudioToolbox.framework */, + 686357CF14100ADB00DF4CF2 /* AVFoundation.framework */, + 686357D014100ADE00DF4CF2 /* CoreLocation.framework */, + 686357D214100AE700DF4CF2 /* MobileCoreServices.framework */, + 686357D414100AF200DF4CF2 /* SystemConfiguration.framework */, + 686357CC14100AAD00DF4CF2 /* AddressBookUI.framework */, + 686357AA141002F100DF4CF2 /* UIKit.framework */, + 686357AC141002F100DF4CF2 /* Foundation.framework */, + 686357AE141002F100DF4CF2 /* CoreGraphics.framework */, + ); + name = Frameworks; + sourceTree = "<group>"; + }; + 3054098714B77FF3009841CA /* Cleaver */ = { + isa = PBXGroup; + children = ( + F858FBC4166009A8007DA594 /* CDVConfigParser.h */, + F858FBC5166009A8007DA594 /* CDVConfigParser.m */, + 8852C43614B65FD800F0E735 /* CDVViewController.h */, + 8852C43714B65FD800F0E735 /* CDVViewController.m */, + EB3B3545161CB44D003DBE7D /* CDVCommandQueue.h */, + EB3B3546161CB44D003DBE7D /* CDVCommandQueue.m */, + ); + name = Cleaver; + sourceTree = "<group>"; + }; + 32C88DFF0371C24200C91783 /* Other Sources */ = { + isa = PBXGroup; + children = ( + AA747D9E0F9514B9006C5449 /* CordovaLib_Prefix.pch */, + ); + name = "Other Sources"; + sourceTree = "<group>"; + }; + 888700D710922F56009987E8 /* Commands */ = { + isa = PBXGroup; + children = ( + 30E6B8CB1A8ADD900025B9EE /* CDVHandleOpenURL.h */, + 30E6B8CC1A8ADD900025B9EE /* CDVHandleOpenURL.m */, + 7E22B88419E4C0210026F95E /* CDVAvailabilityDeprecated.h */, + EBFF4DBA16D3FE2E008F452B /* CDVWebViewDelegate.m */, + EBFF4DBB16D3FE2E008F452B /* CDVWebViewDelegate.h */, + 301F2F2914F3C9CA003FE9FC /* CDV.h */, + 3034979A1513D56A0090E688 /* CDVLocalStorage.h */, + 3034979B1513D56A0090E688 /* CDVLocalStorage.m */, + 30392E4D14F4FCAB00B9E0B8 /* CDVAvailability.h */, + 30F5EBA914CA26E700987760 /* CDVCommandDelegate.h */, + EB3B357A161F2A44003DBE7D /* CDVCommandDelegateImpl.h */, + EB3B357B161F2A45003DBE7D /* CDVCommandDelegateImpl.m */, + 30C684921407044A004C1A8E /* CDVURLProtocol.h */, + 30C684931407044A004C1A8E /* CDVURLProtocol.m */, + 30C6847E1406CB38004C1A8E /* CDVWhitelist.h */, + 1B701026177A61CF00AE11F4 /* CDVShared.h */, + 30C6847F1406CB38004C1A8E /* CDVWhitelist.m */, + 30E33AF013A7E24B00594D64 /* CDVPlugin.h */, + 30E33AF113A7E24B00594D64 /* CDVPlugin.m */, + 1F92F49E1314023E0046367C /* CDVPluginResult.h */, + 1F92F49F1314023E0046367C /* CDVPluginResult.m */, + 8887FD341090FBE7009987E8 /* CDVInvokedUrlCommand.h */, + 8887FD351090FBE7009987E8 /* CDVInvokedUrlCommand.m */, + 3073E9EC1656D51200957977 /* CDVScreenOrientationDelegate.h */, + 30F39309169F839700B22307 /* CDVJSON.h */, + 30F3930A169F839700B22307 /* CDVJSON.m */, + EB6A98521A77EE470013FCDB /* CDVJSON_private.m */, + EB6A98531A77EE470013FCDB /* CDVJSON_private.h */, + EB96673916A8970900D86CDF /* CDVUserAgentUtil.h */, + EB96673A16A8970900D86CDF /* CDVUserAgentUtil.m */, + ); + name = Commands; + sourceTree = "<group>"; + }; + 888700D910923009009987E8 /* Util */ = { + isa = PBXGroup; + children = ( + 3062D11E151D0EDB000D9128 /* UIDevice+Extensions.h */, + 3062D11F151D0EDB000D9128 /* UIDevice+Extensions.m */, + EBA3557115ABD38C00F4DE24 /* NSArray+Comparisons.h */, + EBA3557215ABD38C00F4DE24 /* NSArray+Comparisons.m */, + 8887FD281090FBE7009987E8 /* NSDictionary+Extensions.h */, + 8887FD291090FBE7009987E8 /* NSDictionary+Extensions.m */, + 302965BB13A94E9D007046C5 /* CDVDebug.h */, + 30E563CD13E217EC00C949AA /* NSMutableArray+QueueAdditions.h */, + 30E563CE13E217EC00C949AA /* NSMutableArray+QueueAdditions.m */, + 8887FD501090FBE7009987E8 /* NSData+Base64.h */, + 8887FD511090FBE7009987E8 /* NSData+Base64.m */, + 7E14B5A61705050A0032169E /* CDVTimer.h */, + 7E14B5A71705050A0032169E /* CDVTimer.m */, + ); + name = Util; + sourceTree = "<group>"; + }; + 8887FD101090FB43009987E8 /* Classes */ = { + isa = PBXGroup; + children = ( + 3054098714B77FF3009841CA /* Cleaver */, + 888700D710922F56009987E8 /* Commands */, + 888700D910923009009987E8 /* Util */, + ); + name = Classes; + sourceTree = "<group>"; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + D2AAC07A0554694100DB518D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 8887FD681090FBE7009987E8 /* NSDictionary+Extensions.h in Headers */, + 8887FD741090FBE7009987E8 /* CDVInvokedUrlCommand.h in Headers */, + 8887FD8F1090FBE7009987E8 /* NSData+Base64.h in Headers */, + 1F92F4A01314023E0046367C /* CDVPluginResult.h in Headers */, + 30E33AF213A7E24B00594D64 /* CDVPlugin.h in Headers */, + 30E6B8CD1A8ADD900025B9EE /* CDVHandleOpenURL.h in Headers */, + 302965BC13A94E9D007046C5 /* CDVDebug.h in Headers */, + 30E563CF13E217EC00C949AA /* NSMutableArray+QueueAdditions.h in Headers */, + 30C684801406CB38004C1A8E /* CDVWhitelist.h in Headers */, + 30C684941407044B004C1A8E /* CDVURLProtocol.h in Headers */, + 8852C43A14B65FD800F0E735 /* CDVViewController.h in Headers */, + 30F5EBAB14CA26E700987760 /* CDVCommandDelegate.h in Headers */, + 301F2F2A14F3C9CA003FE9FC /* CDV.h in Headers */, + 30392E4E14F4FCAB00B9E0B8 /* CDVAvailability.h in Headers */, + 7E22B88519E4C0210026F95E /* CDVAvailabilityDeprecated.h in Headers */, + 3034979C1513D56A0090E688 /* CDVLocalStorage.h in Headers */, + 3062D120151D0EDB000D9128 /* UIDevice+Extensions.h in Headers */, + EBA3557315ABD38C00F4DE24 /* NSArray+Comparisons.h in Headers */, + EB3B3547161CB44D003DBE7D /* CDVCommandQueue.h in Headers */, + EB3B357C161F2A45003DBE7D /* CDVCommandDelegateImpl.h in Headers */, + 1B701028177A61CF00AE11F4 /* CDVShared.h in Headers */, + 3073E9ED1656D51200957977 /* CDVScreenOrientationDelegate.h in Headers */, + F858FBC6166009A8007DA594 /* CDVConfigParser.h in Headers */, + 30F3930B169F839700B22307 /* CDVJSON.h in Headers */, + EBFF4DBD16D3FE2E008F452B /* CDVWebViewDelegate.h in Headers */, + EB96673B16A8970A00D86CDF /* CDVUserAgentUtil.h in Headers */, + 7E14B5A81705050A0032169E /* CDVTimer.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 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 = 0510; + }; + buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "CordovaLib" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + en, + ); + mainGroup = 0867D691FE84028FC02AAC07 /* CordovaLib */; + productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + D2AAC07D0554694100DB518D /* CordovaLib */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + D2AAC07B0554694100DB518D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8887FD691090FBE7009987E8 /* NSDictionary+Extensions.m in Sources */, + 8887FD751090FBE7009987E8 /* CDVInvokedUrlCommand.m in Sources */, + 8887FD901090FBE7009987E8 /* NSData+Base64.m in Sources */, + 1F92F4A11314023E0046367C /* CDVPluginResult.m in Sources */, + 30E33AF313A7E24B00594D64 /* CDVPlugin.m in Sources */, + 30E563D013E217EC00C949AA /* NSMutableArray+QueueAdditions.m in Sources */, + 30C684821406CB38004C1A8E /* CDVWhitelist.m in Sources */, + 30C684961407044B004C1A8E /* CDVURLProtocol.m in Sources */, + 8852C43C14B65FD800F0E735 /* CDVViewController.m in Sources */, + 3034979E1513D56A0090E688 /* CDVLocalStorage.m in Sources */, + 3062D122151D0EDB000D9128 /* UIDevice+Extensions.m in Sources */, + EBA3557515ABD38C00F4DE24 /* NSArray+Comparisons.m in Sources */, + EB3B3548161CB44D003DBE7D /* CDVCommandQueue.m in Sources */, + EB6A98541A77EE470013FCDB /* CDVJSON_private.m in Sources */, + EB3B357D161F2A45003DBE7D /* CDVCommandDelegateImpl.m in Sources */, + F858FBC7166009A8007DA594 /* CDVConfigParser.m in Sources */, + 30F3930C169F839700B22307 /* CDVJSON.m in Sources */, + EB96673C16A8970A00D86CDF /* CDVUserAgentUtil.m in Sources */, + 30E6B8CE1A8ADD900025B9EE /* CDVHandleOpenURL.m in Sources */, + EBFF4DBC16D3FE2E008F452B /* CDVWebViewDelegate.m in Sources */, + 7E14B5A91705050A0032169E /* CDVTimer.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 1DEB921F08733DC00010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_OBJC_ARC = YES; + COPY_PHASE_STRIP = NO; + DSTROOT = "/tmp/$(PROJECT_NAME).dst"; + GCC_DYNAMIC_NO_PIC = NO; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = CordovaLib_Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ""; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + INSTALL_PATH = /usr/local/lib; + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + PRODUCT_NAME = Cordova; + PUBLIC_HEADERS_FOLDER_PATH = include/Cordova; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 1DEB922008733DC00010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_OBJC_ARC = YES; + DSTROOT = "/tmp/$(PROJECT_NAME).dst"; + GCC_MODEL_TUNING = G5; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = CordovaLib_Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ""; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + INSTALL_PATH = /usr/local/lib; + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + PRODUCT_NAME = Cordova; + PUBLIC_HEADERS_FOLDER_PATH = include/Cordova; + SKIP_INSTALL = YES; + }; + name = Release; + }; + 1DEB922308733DC00010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ""; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + 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; + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + ONLY_ACTIVE_ARCH = YES; + OTHER_CFLAGS = "-DDEBUG"; + PUBLIC_HEADERS_FOLDER_PATH = include/Cordova; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = ""; + }; + name = Debug; + }; + 1DEB922408733DC00010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_PREPROCESSOR_DEFINITIONS = ""; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + 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; + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + ONLY_ACTIVE_ARCH = NO; + PUBLIC_HEADERS_FOLDER_PATH = include/Cordova; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + 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; + }; +/* End XCConfigurationList section */ + }; + rootObject = 0867D690FE84028FC02AAC07 /* Project object */; +} diff --git a/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/CordovaLib.xcscheme b/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/CordovaLib.xcscheme new file mode 100644 index 00000000..5dce491f --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/CordovaLib.xcscheme @@ -0,0 +1,77 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Scheme + LastUpgradeVersion = "0640" + version = "1.3"> + <BuildAction + parallelizeBuildables = "YES" + buildImplicitDependencies = "YES"> + <BuildActionEntries> + <BuildActionEntry + buildForTesting = "YES" + buildForRunning = "YES" + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "D2AAC07D0554694100DB518D" + BuildableName = "libCordova.a" + BlueprintName = "CordovaLib" + ReferencedContainer = "container:CordovaLib.xcodeproj"> + </BuildableReference> + </BuildActionEntry> + </BuildActionEntries> + </BuildAction> + <TestAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES" + buildConfiguration = "Debug"> + <Testables> + </Testables> + </TestAction> + <LaunchAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Debug" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + allowLocationSimulation = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "D2AAC07D0554694100DB518D" + BuildableName = "libCordova.a" + BlueprintName = "CordovaLib" + ReferencedContainer = "container:CordovaLib.xcodeproj"> + </BuildableReference> + </MacroExpansion> + <AdditionalOptions> + </AdditionalOptions> + </LaunchAction> + <ProfileAction + shouldUseLaunchSchemeArgsEnv = "YES" + savedToolIdentifier = "" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Release" + debugDocumentVersioning = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "D2AAC07D0554694100DB518D" + BuildableName = "libCordova.a" + BlueprintName = "CordovaLib" + ReferencedContainer = "container:CordovaLib.xcodeproj"> + </BuildableReference> + </MacroExpansion> + </ProfileAction> + <AnalyzeAction + buildConfiguration = "Debug"> + </AnalyzeAction> + <ArchiveAction + buildConfiguration = "Release" + revealArchiveInOrganizer = "YES"> + </ArchiveAction> +</Scheme> diff --git a/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/xcschememanagement.plist b/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000..283503be --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,22 @@ +<?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>CordovaLib.xcscheme</key> + <dict> + <key>orderHint</key> + <integer>1</integer> + </dict> + </dict> + <key>SuppressBuildableAutocreation</key> + <dict> + <key>D2AAC07D0554694100DB518D</key> + <dict> + <key>primary</key> + <true/> + </dict> + </dict> +</dict> +</plist> diff --git a/StoneIsland/platforms/ios/CordovaLib/CordovaLib_Prefix.pch b/StoneIsland/platforms/ios/CordovaLib/CordovaLib_Prefix.pch new file mode 100644 index 00000000..95455807 --- /dev/null +++ b/StoneIsland/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> +#endif diff --git a/StoneIsland/platforms/ios/CordovaLib/VERSION b/StoneIsland/platforms/ios/CordovaLib/VERSION new file mode 100644 index 00000000..19811903 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/VERSION @@ -0,0 +1 @@ +3.8.0 diff --git a/StoneIsland/platforms/ios/CordovaLib/cordova.js b/StoneIsland/platforms/ios/CordovaLib/cordova.js new file mode 100644 index 00000000..4f781077 --- /dev/null +++ b/StoneIsland/platforms/ios/CordovaLib/cordova.js @@ -0,0 +1,1810 @@ +// Platform: ios +// fc4db9145934bd0053161cbf9ffc0caf83b770c6 +/* + 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 = '3.8.0'; +// file: src/scripts/require.js + +/*jshint -W079 */ +/*jshint -W020 */ + +var require, + define; + +(function () { + var modules = {}, + // Stack of moduleIds currently being built. + requireStack = [], + // Map of module ID -> index into requireStack of modules currently being built. + inProgressModules = {}, + SEPARATOR = "."; + + + + function build(module) { + var factory = module.factory, + 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 (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) { + + +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 = {}, + 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); + 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 exec = require('cordova/exec'); +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 (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex]; +} + +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), + cUpper = c.toUpperCase(), + 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 = typeof atob != 'undefined' ? atob(str) : new Buffer(str,'base64').toString('binary'); + 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) { + exports.replaceHookForTesting(obj, key); + 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; +exports.replaceHookForTesting = function() {}; + +}); + +// file: src/common/channel.js +define("cordova/channel", function(require, exports, module) { + +var utils = require('cordova/utils'), + 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; +}, + 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, + i = len, + 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 forceFunction(f) { + if (typeof f != 'function') throw "Function required as first argument!"; +} + +/** + * 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(f, c) { + // need a function to call + forceFunction(f); + if (this.state == 2) { + f.apply(c || this, this.fireArgs); + return; + } + + var func = f, + guid = f.observer_guid; + if (typeof c == "object") { func = utils.close(c, f); } + + if (!guid) { + // first time any channel has seen this subscriber + guid = '' + nextGuid++; + } + func.observer_guid = guid; + f.observer_guid = guid; + + // Don't add the same handler more than once. + if (!this.handlers[guid]) { + this.handlers[guid] = func; + this.numHandlers++; + if (this.numHandlers == 1) { + this.onHasSubscribersChange && this.onHasSubscribersChange(); + } + } +}; + +/** + * Unsubscribes the function with the given guid from the channel. + */ +Channel.prototype.unsubscribe = function(f) { + // need a function to unsubscribe + forceFunction(f); + + var guid = f.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 fail = false, + 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: src/ios/exec.js +define("cordova/exec", function(require, exports, module) { + +/** + * Creates a gap bridge iframe used to notify the native code about queued + * commands. + */ +var cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + base64 = require('cordova/base64'), + // XHR mode does not work on iOS 4.2. + // XHR mode's main advantage is working around a bug in -webkit-scroll, which + // doesn't exist only on iOS 5.x devices. + // IFRAME_NAV is the fastest. + // IFRAME_HASH could be made to enable synchronous bridge calls if we wanted this feature. + jsToNativeModes = { + IFRAME_NAV: 0, // Default. Uses a new iframe for each poke. + // XHR bridge appears to be flaky sometimes: CB-3900, CB-3359, CB-5457, CB-4970, CB-4998, CB-5134 + XHR_NO_PAYLOAD: 1, // About the same speed as IFRAME_NAV. Performance not about the same as IFRAME_NAV, but more variable. + XHR_WITH_PAYLOAD: 2, // Flakey, and not as performant + XHR_OPTIONAL_PAYLOAD: 3, // Flakey, and not as performant + IFRAME_HASH_NO_PAYLOAD: 4, // Not fully baked. A bit faster than IFRAME_NAV, but risks jank since poke happens synchronously. + IFRAME_HASH_WITH_PAYLOAD: 5, // Slower than no payload. Maybe since it has to be URI encoded / decoded. + WK_WEBVIEW_BINDING: 6 // Only way that works for WKWebView :) + }, + bridgeMode, + execIframe, + execHashIframe, + hashToggle = 1, + execXhr, + requestCount = 0, + vcHeaderValue = null, + commandQueue = [], // Contains pending JS->Native messages. + isInContextOfEvalJs = 0, + failSafeTimerId = 0; + +function shouldBundleCommandJson() { + if (bridgeMode === jsToNativeModes.XHR_WITH_PAYLOAD) { + return true; + } + if (bridgeMode === jsToNativeModes.XHR_OPTIONAL_PAYLOAD) { + var payloadLength = 0; + for (var i = 0; i < commandQueue.length; ++i) { + payloadLength += commandQueue[i].length; + } + // The value here was determined using the benchmark within CordovaLibApp on an iPad 3. + return payloadLength < 4500; + } + return false; +} + +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() { + if (bridgeMode === undefined) { + bridgeMode = jsToNativeModes.IFRAME_NAV; + } + + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) { + bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING; + } + + var successCallback, failCallback, service, action, actionArgs, splitCommand; + 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 { + // FORMAT TWO, REMOVED + try { + splitCommand = arguments[0].split("."); + action = splitCommand.pop(); + service = splitCommand.join("."); + actionArgs = Array.prototype.splice.call(arguments, 1); + + console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + + "cordova.exec(null, null, \"" + service + "\", \"" + action + "\"," + JSON.stringify(actionArgs) + ");" + ); + return; + } catch (e) {} + } + + // 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 (bridgeMode === jsToNativeModes.WK_WEBVIEW_BINDING) { + window.webkit.messageHandlers.cordova.postMessage(command); + } else { + // 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(); + } + } +} + +function pokeNative() { + switch (bridgeMode) { + case jsToNativeModes.XHR_NO_PAYLOAD: + case jsToNativeModes.XHR_WITH_PAYLOAD: + case jsToNativeModes.XHR_OPTIONAL_PAYLOAD: + pokeNativeViaXhr(); + break; + default: // iframe-based. + pokeNativeViaIframe(); + } +} + +function pokeNativeViaXhr() { + // This prevents sending an XHR when there is already one being sent. + // This should happen only in rare circumstances (refer to unit tests). + if (execXhr && execXhr.readyState != 4) { + execXhr = null; + } + // Re-using the XHR improves exec() performance by about 10%. + execXhr = execXhr || new XMLHttpRequest(); + // Changing this to a GET will make the XHR reach the URIProtocol on 4.2. + // For some reason it still doesn't work though... + // Add a timestamp to the query param to prevent caching. + execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true); + if (!vcHeaderValue) { + vcHeaderValue = /.*\((.*)\)$/.exec(navigator.userAgent)[1]; + } + execXhr.setRequestHeader('vc', vcHeaderValue); + execXhr.setRequestHeader('rc', ++requestCount); + if (shouldBundleCommandJson()) { + execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages()); + } + execXhr.send(null); +} + +function pokeNativeViaIframe() { + // CB-5488 - Don't attempt to create iframe before document.body is available. + if (!document.body) { + setTimeout(pokeNativeViaIframe); + return; + } + if (bridgeMode === jsToNativeModes.IFRAME_HASH_NO_PAYLOAD || bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + // TODO: This bridge mode doesn't properly support being removed from the DOM (CB-7735) + if (!execHashIframe) { + execHashIframe = document.createElement('iframe'); + execHashIframe.style.display = 'none'; + document.body.appendChild(execHashIframe); + // Hash changes don't work on about:blank, so switch it to file:///. + execHashIframe.contentWindow.history.replaceState(null, null, 'file:///#'); + } + // The delegate method is called only when the hash changes, so toggle it back and forth. + hashToggle = hashToggle ^ 3; + var hashValue = '%0' + hashToggle; + if (bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + hashValue += iOSExec.nativeFetchMessages(); + } + execHashIframe.contentWindow.location.hash = hashValue; + } else { + // 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) { + pokeNative(); + } + }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire). + } +} + +iOSExec.jsToNativeModes = jsToNativeModes; + +iOSExec.setJsToNativeBridgeMode = function(mode) { + // Remove the iFrame since it may be no longer required, and its existence + // can trigger browser bugs. + // https://issues.apache.org/jira/browse/CB-593 + if (execIframe) { + if (execIframe.parentNode) { + execIframe.parentNode.removeChild(execIframe); + } + execIframe = null; + } + bridgeMode = mode; +}; + +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) { + return iOSExec.nativeEvalAndFetch(function() { + var success = status === 0 || status === 1; + var args = convertMessageToArgsNativeToJs(message); + cordova.callbackFromNative(callbackId, success, status, args, keepCallback); + }); +}; + +iOSExec.nativeEvalAndFetch = function(func) { + // This shouldn't be nested, but better to be safe. + isInContextOfEvalJs++; + try { + func(); + return iOSExec.nativeFetchMessages(); + } finally { + isInContextOfEvalJs--; + } +}; + +module.exports = iOSExec; + +}); + +// 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.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/init_b.js +define("cordova/init_b", function(require, exports, module) { + +var channel = require('cordova/channel'); +var cordova = require('cordova'); +var platform = require('cordova/platform'); +var utils = require('cordova/utils'); + +var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady]; + +// setting exec +cordova.exec = require('cordova/exec'); + +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.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(); +} + +// Call the platform-specific initialization. +platform.bootstrap && platform.bootstrap(); + +/** + * Create all cordova objects once native side is ready. + */ +channel.join(function() { + + 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'), + moduleMap = define.moduleMap, + symbolList, + 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; + } + var parts = symbolPath.split('.'); + var cur = context; + for (var i = 0, part; part = parts[i]; ++i) { + cur = cur[part] = cur[part] || {}; + } + return cur; +} + +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: src/ios/platform.js +define("cordova/platform", function(require, exports, module) { + +module.exports = { + id: 'ios', + bootstrap: function() { + require('cordova/channel').onNativeReady.fire(); + } +}; + + +}); + +// file: src/common/pluginloader.js +define("cordova/pluginloader", function(require, exports, module) { + +var modulemapper = require('cordova/modulemapper'); +var urlutil = require('cordova/urlutil'); + +// 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 = function(a) { + return utils.typeName(a) == 'Array'; +}; + +/** + * Returns an indication of whether the argument is a Date or not + */ +utils.isDate = function(d) { + return utils.typeName(d) == '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){ + if(!(i in retVal) || retVal[i] != obj[i]) { + retVal[i] = utils.clone(obj[i]); + } + } + return retVal; +}; + +/** + * Returns a wrapped version of the function + */ +utils.close = function(context, func, params) { + if (typeof params == 'undefined') { + return function() { + return func.apply(context, arguments); + }; + } else { + return function() { + return func.apply(context, params); + }; + } +}; + +/** + * 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); + } +}; + + +//------------------------------------------------------------------------------ +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; +} + + +}); + +window.cordova = require('cordova'); +// file: src/scripts/bootstrap.js + +require('cordova/init'); + +})();
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.pbxproj b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.pbxproj new file mode 100644 index 00000000..b1a129c4 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.pbxproj @@ -0,0 +1,650 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { +/* Begin PBXBuildFile section */ + 1D3623260D0F684500981E51 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* AppDelegate.m */; }; + 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; + 288765FD0DF74451002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765FC0DF74451002DB57D /* CoreGraphics.framework */; }; + 301BF552109A68D80062928A /* libCordova.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF535109A57CC0062928A /* libCordova.a */; }; + 302D95F114D2391D003F00A1 /* MainViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 302D95EF14D2391D003F00A1 /* MainViewController.m */; }; + 302D95F214D2391D003F00A1 /* MainViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 302D95F014D2391D003F00A1 /* MainViewController.xib */; }; + 305D5FD1115AB8F900A74A75 /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 305D5FD0115AB8F900A74A75 /* MobileCoreServices.framework */; }; + 3088BBBD154F3926009F9C59 /* Default-Landscape@2x~ipad.png in Resources */ = {isa = PBXBuildFile; fileRef = 3088BBB7154F3926009F9C59 /* Default-Landscape@2x~ipad.png */; }; + 3088BBBE154F3926009F9C59 /* Default-Landscape~ipad.png in Resources */ = {isa = PBXBuildFile; fileRef = 3088BBB8154F3926009F9C59 /* Default-Landscape~ipad.png */; }; + 3088BBBF154F3926009F9C59 /* Default-Portrait@2x~ipad.png in Resources */ = {isa = PBXBuildFile; fileRef = 3088BBB9154F3926009F9C59 /* Default-Portrait@2x~ipad.png */; }; + 3088BBC0154F3926009F9C59 /* Default-Portrait~ipad.png in Resources */ = {isa = PBXBuildFile; fileRef = 3088BBBA154F3926009F9C59 /* Default-Portrait~ipad.png */; }; + 3088BBC1154F3926009F9C59 /* Default@2x~iphone.png in Resources */ = {isa = PBXBuildFile; fileRef = 3088BBBB154F3926009F9C59 /* Default@2x~iphone.png */; }; + 3088BBC2154F3926009F9C59 /* Default~iphone.png in Resources */ = {isa = PBXBuildFile; fileRef = 3088BBBC154F3926009F9C59 /* Default~iphone.png */; }; + 308D05371370CCF300D202BF /* icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = 308D052E1370CCF300D202BF /* icon-72.png */; }; + 308D05381370CCF300D202BF /* icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 308D052F1370CCF300D202BF /* icon.png */; }; + 308D05391370CCF300D202BF /* icon@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 308D05301370CCF300D202BF /* icon@2x.png */; }; + 30B4F30019D5E07200D9F7D8 /* Default-667h.png in Resources */ = {isa = PBXBuildFile; fileRef = 30B4F2FD19D5E07200D9F7D8 /* Default-667h.png */; }; + 30B4F30119D5E07200D9F7D8 /* Default-736h.png in Resources */ = {isa = PBXBuildFile; fileRef = 30B4F2FE19D5E07200D9F7D8 /* Default-736h.png */; }; + 30B4F30219D5E07200D9F7D8 /* Default-Landscape-736h.png in Resources */ = {isa = PBXBuildFile; fileRef = 30B4F2FF19D5E07200D9F7D8 /* Default-Landscape-736h.png */; }; + 30C1856619D5FC0A00212699 /* icon-60@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = 30C1856519D5FC0A00212699 /* icon-60@3x.png */; }; + 30FC414916E50CA1004E6F35 /* icon-72@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 30FC414816E50CA1004E6F35 /* icon-72@2x.png */; }; + 5B1594DD16A7569C00FEF299 /* AssetsLibrary.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */; }; + 7E7966DE1810823500FA85AD /* icon-40.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D41810823500FA85AD /* icon-40.png */; }; + 7E7966DF1810823500FA85AD /* icon-40@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D51810823500FA85AD /* icon-40@2x.png */; }; + 7E7966E01810823500FA85AD /* icon-50.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D61810823500FA85AD /* icon-50.png */; }; + 7E7966E11810823500FA85AD /* icon-50@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D71810823500FA85AD /* icon-50@2x.png */; }; + 7E7966E21810823500FA85AD /* icon-60.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D81810823500FA85AD /* icon-60.png */; }; + 7E7966E31810823500FA85AD /* icon-60@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D91810823500FA85AD /* icon-60@2x.png */; }; + 7E7966E41810823500FA85AD /* icon-76.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DA1810823500FA85AD /* icon-76.png */; }; + 7E7966E51810823500FA85AD /* icon-76@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DB1810823500FA85AD /* icon-76@2x.png */; }; + 7E7966E61810823500FA85AD /* icon-small.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DC1810823500FA85AD /* icon-small.png */; }; + 7E7966E71810823500FA85AD /* icon-small@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DD1810823500FA85AD /* icon-small@2x.png */; }; + D4A0D8761607E02300AEF8BB /* Default-568h@2x~iphone.png in Resources */ = {isa = PBXBuildFile; fileRef = D4A0D8751607E02300AEF8BB /* Default-568h@2x~iphone.png */; }; + 6C75E778743C4F5CA277F5DF /* IonicKeyboard.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AB740C9CDB74872B20A4614 /* IonicKeyboard.m */; }; + 11EA6033F2FA495F845B1657 /* UIWebViewExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 1AD560161AD74255B8667033 /* UIWebViewExtension.m */; }; + 41BAFFE4C42D41DD968BBB78 /* CDVLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = BB02E36AE3B54CC68B5024AF /* CDVLogger.m */; }; + 60B7E5E0CB244521B6DD1796 /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = 943E2FA542FB4539881F232C /* CDVDevice.m */; }; + BA9047DFE2184BAB88064B59 /* CDVNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = B295AC38A16E468B93376948 /* CDVNotification.m */; }; + DD4E2F77BF0F4B7E866D8B5A /* CDVNotification.bundle in Resources */ = {isa = PBXBuildFile; fileRef = A3784F401BE74727A65E95BA /* CDVNotification.bundle */; }; + 05EBE3ED6EA64212BCC52906 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 270ADA31CA7B4A42B185E451 /* AudioToolbox.framework */; settings = {ATTRIBUTES = (Weak, ); }; }; + 4F159639E85C4AA6A6586124 /* CDVLocation.m in Sources */ = {isa = PBXBuildFile; fileRef = 8DB5B5B7FD894F31AEE2DE28 /* CDVLocation.m */; }; + 85552B118FDD4F9286C3D33C /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 88109882DED84831BEC5BBB0 /* CoreLocation.framework */; }; + 28A1910A7DEA48DBB4EBB8FA /* CDVConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = E0B03F2F75BD419ABA4A9689 /* CDVConnection.m */; }; + 79E64CBE70114745BC7D1E61 /* CDVReachability.m in Sources */ = {isa = PBXBuildFile; fileRef = E7E73D045C374F719137889D /* CDVReachability.m */; }; + 28FA0D2F417F4E6891D4A2A3 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E63CFDA045E649E8A2E41A6E /* SystemConfiguration.framework */; settings = {ATTRIBUTES = (Weak, ); }; }; + 032ABF0840BB48E0B3DD2F92 /* CDVSplashScreen.m in Sources */ = {isa = PBXBuildFile; fileRef = 73C53A36FBD446C9BB33C265 /* CDVSplashScreen.m */; }; + C2BF0352F9A246A886C16676 /* CDVViewController+SplashScreen.m in Sources */ = {isa = PBXBuildFile; fileRef = 58B5B2F329484022BEE14D58 /* CDVViewController+SplashScreen.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; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 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 /* StoneIsland.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "StoneIsland.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 1F766FDD13BBADB100FB74C0 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = Localizable.strings; sourceTree = "<group>"; }; + 1F766FE013BBADB100FB74C0 /* es */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = es; path = Localizable.strings; sourceTree = "<group>"; }; + 288765FC0DF74451002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 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>"; }; + 305D5FD0115AB8F900A74A75 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = System/Library/Frameworks/MobileCoreServices.framework; sourceTree = SDKROOT; }; + 3088BBB7154F3926009F9C59 /* Default-Landscape@2x~ipad.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-Landscape@2x~ipad.png"; sourceTree = "<group>"; }; + 3088BBB8154F3926009F9C59 /* Default-Landscape~ipad.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-Landscape~ipad.png"; sourceTree = "<group>"; }; + 3088BBB9154F3926009F9C59 /* Default-Portrait@2x~ipad.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-Portrait@2x~ipad.png"; sourceTree = "<group>"; }; + 3088BBBA154F3926009F9C59 /* Default-Portrait~ipad.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-Portrait~ipad.png"; sourceTree = "<group>"; }; + 3088BBBB154F3926009F9C59 /* Default@2x~iphone.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x~iphone.png"; sourceTree = "<group>"; }; + 3088BBBC154F3926009F9C59 /* Default~iphone.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default~iphone.png"; sourceTree = "<group>"; }; + 308D052E1370CCF300D202BF /* icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-72.png"; sourceTree = "<group>"; }; + 308D052F1370CCF300D202BF /* icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = icon.png; sourceTree = "<group>"; }; + 308D05301370CCF300D202BF /* icon@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon@2x.png"; sourceTree = "<group>"; }; + 30B4F2FD19D5E07200D9F7D8 /* Default-667h.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-667h.png"; sourceTree = "<group>"; }; + 30B4F2FE19D5E07200D9F7D8 /* Default-736h.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-736h.png"; sourceTree = "<group>"; }; + 30B4F2FF19D5E07200D9F7D8 /* Default-Landscape-736h.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-Landscape-736h.png"; sourceTree = "<group>"; }; + 30C1856519D5FC0A00212699 /* icon-60@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-60@3x.png"; sourceTree = "<group>"; }; + 30FC414816E50CA1004E6F35 /* icon-72@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-72@2x.png"; sourceTree = "<group>"; }; + 32CA4F630368D1EE00C91783 /* StoneIsland-Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "StoneIsland-Prefix.pch"; sourceTree = "<group>"; }; + 5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AssetsLibrary.framework; path = System/Library/Frameworks/AssetsLibrary.framework; sourceTree = SDKROOT; }; + 7E7966D41810823500FA85AD /* icon-40.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-40.png"; sourceTree = "<group>"; }; + 7E7966D51810823500FA85AD /* icon-40@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-40@2x.png"; sourceTree = "<group>"; }; + 7E7966D61810823500FA85AD /* icon-50.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-50.png"; sourceTree = "<group>"; }; + 7E7966D71810823500FA85AD /* icon-50@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-50@2x.png"; sourceTree = "<group>"; }; + 7E7966D81810823500FA85AD /* icon-60.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-60.png"; sourceTree = "<group>"; }; + 7E7966D91810823500FA85AD /* icon-60@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-60@2x.png"; sourceTree = "<group>"; }; + 7E7966DA1810823500FA85AD /* icon-76.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-76.png"; sourceTree = "<group>"; }; + 7E7966DB1810823500FA85AD /* icon-76@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-76@2x.png"; sourceTree = "<group>"; }; + 7E7966DC1810823500FA85AD /* icon-small.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-small.png"; sourceTree = "<group>"; }; + 7E7966DD1810823500FA85AD /* icon-small@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "icon-small@2x.png"; sourceTree = "<group>"; }; + 8D1107310486CEB800E47090 /* StoneIsland-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "StoneIsland-Info.plist"; path = "../StoneIsland-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = "<group>"; }; + D4A0D8751607E02300AEF8BB /* Default-568h@2x~iphone.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x~iphone.png"; sourceTree = "<group>"; }; + EB87FDF21871DA7A0020F90C /* merges */ = {isa = PBXFileReference; lastKnownFileType = folder; name = merges; path = ../../merges; sourceTree = "<group>"; }; + 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>"; }; + F840E1F0165FE0F500CFE078 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = "StoneIsland/config.xml"; sourceTree = "<group>"; }; + 7AB740C9CDB74872B20A4614 /* IonicKeyboard.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "IonicKeyboard.m"; path = "com.ionic.keyboard/IonicKeyboard.m"; sourceTree = "<group>"; fileEncoding = 4; }; + 1AD560161AD74255B8667033 /* UIWebViewExtension.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "UIWebViewExtension.m"; path = "com.ionic.keyboard/UIWebViewExtension.m"; sourceTree = "<group>"; fileEncoding = 4; }; + CB2B6023F6FA4EDDA1B805A3 /* IonicKeyboard.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "IonicKeyboard.h"; path = "com.ionic.keyboard/IonicKeyboard.h"; sourceTree = "<group>"; fileEncoding = 4; }; + 461C6746FF5D496C905BB2F4 /* UIWebViewExtension.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "UIWebViewExtension.h"; path = "com.ionic.keyboard/UIWebViewExtension.h"; sourceTree = "<group>"; fileEncoding = 4; }; + BB02E36AE3B54CC68B5024AF /* CDVLogger.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVLogger.m"; path = "cordova-plugin-console/CDVLogger.m"; sourceTree = "<group>"; fileEncoding = 4; }; + C0F9083D05D14C36888043CF /* CDVLogger.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVLogger.h"; path = "cordova-plugin-console/CDVLogger.h"; sourceTree = "<group>"; fileEncoding = 4; }; + 943E2FA542FB4539881F232C /* CDVDevice.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVDevice.m"; path = "cordova-plugin-device/CDVDevice.m"; sourceTree = "<group>"; fileEncoding = 4; }; + 21A7639E907549CFB6316B85 /* CDVDevice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVDevice.h"; path = "cordova-plugin-device/CDVDevice.h"; sourceTree = "<group>"; fileEncoding = 4; }; + B295AC38A16E468B93376948 /* CDVNotification.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVNotification.m"; path = "cordova-plugin-dialogs/CDVNotification.m"; sourceTree = "<group>"; fileEncoding = 4; }; + C3742AC53E044C76B51CEE5C /* CDVNotification.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVNotification.h"; path = "cordova-plugin-dialogs/CDVNotification.h"; sourceTree = "<group>"; fileEncoding = 4; }; + A3784F401BE74727A65E95BA /* CDVNotification.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; name = "CDVNotification.bundle"; path = "CDVNotification.bundle"; sourceTree = "<group>"; }; + 270ADA31CA7B4A42B185E451 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = "AudioToolbox.framework"; path = "System/Library/Frameworks/AudioToolbox.framework"; sourceTree = SDKROOT; fileEncoding = 4; }; + 8DB5B5B7FD894F31AEE2DE28 /* CDVLocation.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVLocation.m"; path = "cordova-plugin-geolocation/CDVLocation.m"; sourceTree = "<group>"; fileEncoding = 4; }; + 07C6DBCD51E04D448AAF3C12 /* CDVLocation.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVLocation.h"; path = "cordova-plugin-geolocation/CDVLocation.h"; sourceTree = "<group>"; fileEncoding = 4; }; + 88109882DED84831BEC5BBB0 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = "CoreLocation.framework"; path = "System/Library/Frameworks/CoreLocation.framework"; sourceTree = SDKROOT; fileEncoding = 4; }; + E0B03F2F75BD419ABA4A9689 /* CDVConnection.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVConnection.m"; path = "cordova-plugin-network-information/CDVConnection.m"; sourceTree = "<group>"; fileEncoding = 4; }; + E7E73D045C374F719137889D /* CDVReachability.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVReachability.m"; path = "cordova-plugin-network-information/CDVReachability.m"; sourceTree = "<group>"; fileEncoding = 4; }; + A5AE3F6AD3E84776AEAC2BC0 /* CDVConnection.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVConnection.h"; path = "cordova-plugin-network-information/CDVConnection.h"; sourceTree = "<group>"; fileEncoding = 4; }; + B91BC96D7245451284AE3002 /* CDVReachability.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVReachability.h"; path = "cordova-plugin-network-information/CDVReachability.h"; sourceTree = "<group>"; fileEncoding = 4; }; + E63CFDA045E649E8A2E41A6E /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = "SystemConfiguration.framework"; path = "System/Library/Frameworks/SystemConfiguration.framework"; sourceTree = SDKROOT; fileEncoding = 4; }; + 73C53A36FBD446C9BB33C265 /* CDVSplashScreen.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVSplashScreen.m"; path = "cordova-plugin-splashscreen/CDVSplashScreen.m"; sourceTree = "<group>"; fileEncoding = 4; }; + 58B5B2F329484022BEE14D58 /* CDVViewController+SplashScreen.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = "CDVViewController+SplashScreen.m"; path = "cordova-plugin-splashscreen/CDVViewController+SplashScreen.m"; sourceTree = "<group>"; fileEncoding = 4; }; + 3E6B9A9492B847CD8FE87334 /* CDVSplashScreen.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVSplashScreen.h"; path = "cordova-plugin-splashscreen/CDVSplashScreen.h"; sourceTree = "<group>"; fileEncoding = 4; }; + AEFF8C2B3066438BB4111A39 /* CDVViewController+SplashScreen.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "CDVViewController+SplashScreen.h"; path = "cordova-plugin-splashscreen/CDVViewController+SplashScreen.h"; sourceTree = "<group>"; fileEncoding = 4; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5B1594DD16A7569C00FEF299 /* AssetsLibrary.framework in Frameworks */, + 301BF552109A68D80062928A /* libCordova.a in Frameworks */, + 288765FD0DF74451002DB57D /* CoreGraphics.framework in Frameworks */, + 305D5FD1115AB8F900A74A75 /* MobileCoreServices.framework in Frameworks */, + 05EBE3ED6EA64212BCC52906 /* AudioToolbox.framework in Frameworks */, + 85552B118FDD4F9286C3D33C /* CoreLocation.framework in Frameworks */, + 28FA0D2F417F4E6891D4A2A3 /* SystemConfiguration.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 = "StoneIsland/Classes"; + sourceTree = SOURCE_ROOT; + }; + 19C28FACFE9D520D11CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 1D6058910D05DD3D006BFB54 /* StoneIsland.app */, + ); + name = Products; + sourceTree = "<group>"; + }; + 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { + isa = PBXGroup; + children = ( + EB87FDF41871DAF40020F90C /* config.xml */, + EB87FDF31871DA8E0020F90C /* www */, + EB87FDF21871DA7A0020F90C /* merges */, + 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 /* StoneIsland-Prefix.pch */, + 29B97316FDCFA39411CA2CEA /* main.m */, + ); + name = "Other Sources"; + path = "StoneIsland"; + sourceTree = "<group>"; + }; + 29B97317FDCFA39411CA2CEA /* Resources */ = { + isa = PBXGroup; + children = ( + 308D052D1370CCF300D202BF /* icons */, + 308D05311370CCF300D202BF /* splash */, + 8D1107310486CEB800E47090 /* StoneIsland-Info.plist */, + A3784F401BE74727A65E95BA /* CDVNotification.bundle */, + ); + name = Resources; + path = "StoneIsland/Resources"; + sourceTree = "<group>"; + }; + 29B97323FDCFA39411CA2CEA /* Frameworks */ = { + isa = PBXGroup; + children = ( + 5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */, + 288765FC0DF74451002DB57D /* CoreGraphics.framework */, + 305D5FD0115AB8F900A74A75 /* MobileCoreServices.framework */, + 270ADA31CA7B4A42B185E451 /* AudioToolbox.framework */, + 88109882DED84831BEC5BBB0 /* CoreLocation.framework */, + E63CFDA045E649E8A2E41A6E /* SystemConfiguration.framework */, + ); + name = Frameworks; + sourceTree = "<group>"; + }; + 301BF52E109A57CC0062928A /* Products */ = { + isa = PBXGroup; + children = ( + 301BF535109A57CC0062928A /* libCordova.a */, + ); + name = Products; + sourceTree = "<group>"; + }; + 307C750510C5A3420062BCA9 /* Plugins */ = { + isa = PBXGroup; + children = ( + 7AB740C9CDB74872B20A4614 /* IonicKeyboard.m */, + 1AD560161AD74255B8667033 /* UIWebViewExtension.m */, + CB2B6023F6FA4EDDA1B805A3 /* IonicKeyboard.h */, + 461C6746FF5D496C905BB2F4 /* UIWebViewExtension.h */, + BB02E36AE3B54CC68B5024AF /* CDVLogger.m */, + C0F9083D05D14C36888043CF /* CDVLogger.h */, + 943E2FA542FB4539881F232C /* CDVDevice.m */, + 21A7639E907549CFB6316B85 /* CDVDevice.h */, + B295AC38A16E468B93376948 /* CDVNotification.m */, + C3742AC53E044C76B51CEE5C /* CDVNotification.h */, + 8DB5B5B7FD894F31AEE2DE28 /* CDVLocation.m */, + 07C6DBCD51E04D448AAF3C12 /* CDVLocation.h */, + E0B03F2F75BD419ABA4A9689 /* CDVConnection.m */, + E7E73D045C374F719137889D /* CDVReachability.m */, + A5AE3F6AD3E84776AEAC2BC0 /* CDVConnection.h */, + B91BC96D7245451284AE3002 /* CDVReachability.h */, + 73C53A36FBD446C9BB33C265 /* CDVSplashScreen.m */, + 58B5B2F329484022BEE14D58 /* CDVViewController+SplashScreen.m */, + 3E6B9A9492B847CD8FE87334 /* CDVSplashScreen.h */, + AEFF8C2B3066438BB4111A39 /* CDVViewController+SplashScreen.h */, + ); + name = Plugins; + path = "StoneIsland/Plugins"; + sourceTree = SOURCE_ROOT; + }; + 308D052D1370CCF300D202BF /* icons */ = { + isa = PBXGroup; + children = ( + 30C1856519D5FC0A00212699 /* icon-60@3x.png */, + 7E7966D41810823500FA85AD /* icon-40.png */, + 7E7966D51810823500FA85AD /* icon-40@2x.png */, + 7E7966D61810823500FA85AD /* icon-50.png */, + 7E7966D71810823500FA85AD /* icon-50@2x.png */, + 7E7966D81810823500FA85AD /* icon-60.png */, + 7E7966D91810823500FA85AD /* icon-60@2x.png */, + 7E7966DA1810823500FA85AD /* icon-76.png */, + 7E7966DB1810823500FA85AD /* icon-76@2x.png */, + 7E7966DC1810823500FA85AD /* icon-small.png */, + 7E7966DD1810823500FA85AD /* icon-small@2x.png */, + 30FC414816E50CA1004E6F35 /* icon-72@2x.png */, + 308D052E1370CCF300D202BF /* icon-72.png */, + 308D052F1370CCF300D202BF /* icon.png */, + 308D05301370CCF300D202BF /* icon@2x.png */, + ); + path = icons; + sourceTree = "<group>"; + }; + 308D05311370CCF300D202BF /* splash */ = { + isa = PBXGroup; + children = ( + 30B4F2FD19D5E07200D9F7D8 /* Default-667h.png */, + 30B4F2FE19D5E07200D9F7D8 /* Default-736h.png */, + 30B4F2FF19D5E07200D9F7D8 /* Default-Landscape-736h.png */, + D4A0D8751607E02300AEF8BB /* Default-568h@2x~iphone.png */, + 3088BBB7154F3926009F9C59 /* Default-Landscape@2x~ipad.png */, + 3088BBB8154F3926009F9C59 /* Default-Landscape~ipad.png */, + 3088BBB9154F3926009F9C59 /* Default-Portrait@2x~ipad.png */, + 3088BBBA154F3926009F9C59 /* Default-Portrait~ipad.png */, + 3088BBBB154F3926009F9C59 /* Default@2x~iphone.png */, + 3088BBBC154F3926009F9C59 /* Default~iphone.png */, + ); + path = splash; + sourceTree = "<group>"; + }; + EB87FDF11871DA420020F90C /* Staging */ = { + isa = PBXGroup; + children = ( + F840E1F0165FE0F500CFE078 /* config.xml */, + 301BF56E109A69640062928A /* www */, + ); + name = Staging; + sourceTree = "<group>"; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 1D6058900D05DD3D006BFB54 /* StoneIsland */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "StoneIsland" */; + buildPhases = ( + 304B58A110DAC018002A0835 /* Copy www directory */, + 1D60588D0D05DD3D006BFB54 /* Resources */, + 1D60588E0D05DD3D006BFB54 /* Sources */, + 1D60588F0D05DD3D006BFB54 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 301BF551109A68C00062928A /* PBXTargetDependency */, + ); + name = "StoneIsland"; + productName = "StoneIsland"; + productReference = 1D6058910D05DD3D006BFB54 /* StoneIsland.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 29B97313FDCFA39411CA2CEA /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 510; + }; + buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "__CLI__" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + en, + es, + de, + se, + ); + mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 301BF52E109A57CC0062928A /* Products */; + ProjectRef = 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 1D6058900D05DD3D006BFB54 /* StoneIsland */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 301BF535109A57CC0062928A /* libCordova.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libCordova.a; + remoteRef = 301BF534109A57CC0062928A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 1D60588D0D05DD3D006BFB54 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E7966E41810823500FA85AD /* icon-76.png in Resources */, + 7E7966DF1810823500FA85AD /* icon-40@2x.png in Resources */, + 308D05371370CCF300D202BF /* icon-72.png in Resources */, + 30B4F30119D5E07200D9F7D8 /* Default-736h.png in Resources */, + 308D05381370CCF300D202BF /* icon.png in Resources */, + 308D05391370CCF300D202BF /* icon@2x.png in Resources */, + 302D95F214D2391D003F00A1 /* MainViewController.xib in Resources */, + 7E7966E01810823500FA85AD /* icon-50.png in Resources */, + 7E7966E31810823500FA85AD /* icon-60@2x.png in Resources */, + 7E7966E61810823500FA85AD /* icon-small.png in Resources */, + 3088BBBD154F3926009F9C59 /* Default-Landscape@2x~ipad.png in Resources */, + 3088BBBE154F3926009F9C59 /* Default-Landscape~ipad.png in Resources */, + 3088BBBF154F3926009F9C59 /* Default-Portrait@2x~ipad.png in Resources */, + 7E7966E71810823500FA85AD /* icon-small@2x.png in Resources */, + 3088BBC0154F3926009F9C59 /* Default-Portrait~ipad.png in Resources */, + 30B4F30019D5E07200D9F7D8 /* Default-667h.png in Resources */, + 7E7966DE1810823500FA85AD /* icon-40.png in Resources */, + 3088BBC1154F3926009F9C59 /* Default@2x~iphone.png in Resources */, + 7E7966E21810823500FA85AD /* icon-60.png in Resources */, + 3088BBC2154F3926009F9C59 /* Default~iphone.png in Resources */, + D4A0D8761607E02300AEF8BB /* Default-568h@2x~iphone.png in Resources */, + 30B4F30219D5E07200D9F7D8 /* Default-Landscape-736h.png in Resources */, + 30C1856619D5FC0A00212699 /* icon-60@3x.png in Resources */, + 7E7966E11810823500FA85AD /* icon-50@2x.png in Resources */, + 7E7966E51810823500FA85AD /* icon-76@2x.png in Resources */, + 30FC414916E50CA1004E6F35 /* icon-72@2x.png in Resources */, + DD4E2F77BF0F4B7E866D8B5A /* CDVNotification.bundle 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 = "cordova/lib/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 */, + 6C75E778743C4F5CA277F5DF /* IonicKeyboard.m in Sources */, + 11EA6033F2FA495F845B1657 /* UIWebViewExtension.m in Sources */, + 41BAFFE4C42D41DD968BBB78 /* CDVLogger.m in Sources */, + 60B7E5E0CB244521B6DD1796 /* CDVDevice.m in Sources */, + BA9047DFE2184BAB88064B59 /* CDVNotification.m in Sources */, + 4F159639E85C4AA6A6586124 /* CDVLocation.m in Sources */, + 28A1910A7DEA48DBB4EBB8FA /* CDVConnection.m in Sources */, + 79E64CBE70114745BC7D1E61 /* CDVReachability.m in Sources */, + 032ABF0840BB48E0B3DD2F92 /* CDVSplashScreen.m in Sources */, + C2BF0352F9A246A886C16676 /* CDVViewController+SplashScreen.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; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + 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 = "StoneIsland/StoneIsland-Prefix.pch"; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + INFOPLIST_FILE = "StoneIsland/StoneIsland-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + OTHER_LDFLAGS = ( + "-weak_framework", + CoreFoundation, + "-weak_framework", + UIKit, + "-weak_framework", + AVFoundation, + "-weak_framework", + CoreMedia, + "-weak-lSystem", + "-ObjC", + ); + PRODUCT_NAME = "StoneIsland"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 1D6058950D05DD3E006BFB54 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_OBJC_ARC = YES; + COPY_PHASE_STRIP = YES; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "StoneIsland/StoneIsland-Prefix.pch"; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + INFOPLIST_FILE = "StoneIsland/StoneIsland-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + OTHER_LDFLAGS = ( + "-weak_framework", + CoreFoundation, + "-weak_framework", + UIKit, + "-weak_framework", + AVFoundation, + "-weak_framework", + CoreMedia, + "-weak-lSystem", + "-ObjC", + ); + PRODUCT_NAME = "StoneIsland"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + C01FCF4F08A954540054247B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + 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; + HEADER_SEARCH_PATHS = ( + "\"$(TARGET_BUILD_DIR)/usr/local/lib/include\"", + "\"$(OBJROOT)/UninstalledProducts/include\"", + "\"$(BUILT_PRODUCTS_DIR)\"", + ); + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = ( + "-weak_framework", + CoreFoundation, + "-weak_framework", + UIKit, + "-weak_framework", + AVFoundation, + "-weak_framework", + CoreMedia, + "-weak-lSystem", + "-ObjC", + ); + SDKROOT = iphoneos; + SKIP_INSTALL = NO; + USER_HEADER_SEARCH_PATHS = ""; + }; + name = Debug; + }; + C01FCF5008A954540054247B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_THUMB_SUPPORT = NO; + GCC_VERSION = ""; + 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; + HEADER_SEARCH_PATHS = ( + "\"$(TARGET_BUILD_DIR)/usr/local/lib/include\"", + "\"$(OBJROOT)/UninstalledProducts/include\"", + "\"$(BUILT_PRODUCTS_DIR)\"", + ); + IPHONEOS_DEPLOYMENT_TARGET = 6.0; + OTHER_LDFLAGS = ( + "-weak_framework", + CoreFoundation, + "-weak_framework", + UIKit, + "-weak_framework", + AVFoundation, + "-weak_framework", + CoreMedia, + "-weak-lSystem", + "-ObjC", + ); + SDKROOT = iphoneos; + SKIP_INSTALL = NO; + USER_HEADER_SEARCH_PATHS = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "StoneIsland" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D6058940D05DD3E006BFB54 /* Debug */, + 1D6058950D05DD3E006BFB54 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C01FCF4E08A954540054247B /* Build configuration list for PBXProject "__CLI__" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C01FCF4F08A954540054247B /* Debug */, + C01FCF5008A954540054247B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; +} diff --git a/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Workspace + version = "1.0"> + <FileRef + location = "self:"> + </FileRef> +</Workspace> diff --git a/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.xcworkspace/xcuserdata/jules.xcuserdatad/UserInterfaceState.xcuserstate b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.xcworkspace/xcuserdata/jules.xcuserdatad/UserInterfaceState.xcuserstate Binary files differnew file mode 100644 index 00000000..a5309150 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/project.xcworkspace/xcuserdata/jules.xcuserdatad/UserInterfaceState.xcuserstate diff --git a/StoneIsland/platforms/ios/StoneIsland.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/StoneIsland.xcscheme b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/StoneIsland.xcscheme new file mode 100644 index 00000000..a3634c57 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/StoneIsland.xcscheme @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Scheme + LastUpgradeVersion = "0640" + 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 = "StoneIsland.app" + BlueprintName = "StoneIsland" + ReferencedContainer = "container:StoneIsland.xcodeproj"> + </BuildableReference> + </BuildActionEntry> + </BuildActionEntries> + </BuildAction> + <TestAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES" + buildConfiguration = "Debug"> + <Testables> + </Testables> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "1D6058900D05DD3D006BFB54" + BuildableName = "StoneIsland.app" + BlueprintName = "StoneIsland" + ReferencedContainer = "container:StoneIsland.xcodeproj"> + </BuildableReference> + </MacroExpansion> + </TestAction> + <LaunchAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Debug" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + allowLocationSimulation = "YES"> + <BuildableProductRunnable + runnableDebuggingMode = "0"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "1D6058900D05DD3D006BFB54" + BuildableName = "StoneIsland.app" + BlueprintName = "StoneIsland" + ReferencedContainer = "container:StoneIsland.xcodeproj"> + </BuildableReference> + </BuildableProductRunnable> + <AdditionalOptions> + </AdditionalOptions> + </LaunchAction> + <ProfileAction + shouldUseLaunchSchemeArgsEnv = "YES" + savedToolIdentifier = "" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Release" + debugDocumentVersioning = "YES"> + <BuildableProductRunnable + runnableDebuggingMode = "0"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "1D6058900D05DD3D006BFB54" + BuildableName = "StoneIsland.app" + BlueprintName = "StoneIsland" + ReferencedContainer = "container:StoneIsland.xcodeproj"> + </BuildableReference> + </BuildableProductRunnable> + </ProfileAction> + <AnalyzeAction + buildConfiguration = "Debug"> + </AnalyzeAction> + <ArchiveAction + buildConfiguration = "Release" + revealArchiveInOrganizer = "YES"> + </ArchiveAction> +</Scheme> diff --git a/StoneIsland/platforms/ios/StoneIsland.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/xcschememanagement.plist b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000..fa8991e2 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland.xcodeproj/xcuserdata/jules.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,22 @@ +<?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>StoneIsland.xcscheme</key> + <dict> + <key>orderHint</key> + <integer>0</integer> + </dict> + </dict> + <key>SuppressBuildableAutocreation</key> + <dict> + <key>1D6058900D05DD3D006BFB54</key> + <dict> + <key>primary</key> + <true/> + </dict> + </dict> +</dict> +</plist> diff --git a/StoneIsland/platforms/ios/StoneIsland/.gitignore b/StoneIsland/platforms/ios/StoneIsland/.gitignore new file mode 100644 index 00000000..cc76483f --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/.gitignore @@ -0,0 +1,5 @@ +*.mode1v3 +*.perspectivev3 +*.pbxuser +.DS_Store +build/ diff --git a/StoneIsland/platforms/ios/StoneIsland/Classes/AppDelegate.h b/StoneIsland/platforms/ios/StoneIsland/Classes/AppDelegate.h new file mode 100644 index 00000000..2587ce10 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Classes/AppDelegate.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. + */ + +// +// AppDelegate.h +// HelloCordova +// +// Created by ___FULLUSERNAME___ on ___DATE___. +// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved. +// + +#import <UIKit/UIKit.h> + +#import <Cordova/CDVViewController.h> + +@interface AppDelegate : NSObject <UIApplicationDelegate>{} + +// invoke string is passed to your app on launch, this is only valid if you +// edit HelloCordova-Info.plist to add a protocol +// a simple tutorial can be found here : +// http://iphonedevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html + +@property (nonatomic, strong) IBOutlet UIWindow* window; +@property (nonatomic, strong) IBOutlet CDVViewController* viewController; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Classes/AppDelegate.m b/StoneIsland/platforms/ios/StoneIsland/Classes/AppDelegate.m new file mode 100644 index 00000000..79e57538 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Classes/AppDelegate.m @@ -0,0 +1,151 @@ +/* + 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 +// HelloCordova +// +// Created by ___FULLUSERNAME___ on ___DATE___. +// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved. +// + +#import "AppDelegate.h" +#import "MainViewController.h" + +#import <Cordova/CDVPlugin.h> + +@implementation AppDelegate + +@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 +#if __has_feature(objc_arc) + NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"]; +#else + NSURLCache* sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease]; +#endif + [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]; + +#if __has_feature(objc_arc) + self.window = [[UIWindow alloc] initWithFrame:screenBounds]; +#else + self.window = [[[UIWindow alloc] initWithFrame:screenBounds] autorelease]; +#endif + self.window.autoresizesSubviews = YES; + +#if __has_feature(objc_arc) + self.viewController = [[MainViewController alloc] init]; +#else + self.viewController = [[[MainViewController alloc] init] autorelease]; +#endif + + // 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 HelloCordova-Info.plist specifies a protocol to handle +- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation +{ + if (!url) { + return NO; + } + + // all plugins will get the notification, and their handlers will be called + [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]]; + + return YES; +} + +// repost all remote and local notification using the default NSNotificationCenter so multiple plugins may respond +- (void) application:(UIApplication*)application + didReceiveLocalNotification:(UILocalNotification*)notification +{ + // re-post ( broadcast ) + [[NSNotificationCenter defaultCenter] postNotificationName:CDVLocalNotification object:notification]; +} + +#ifndef DISABLE_PUSH_NOTIFICATIONS + + - (void) application:(UIApplication*)application + didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken + { + // re-post ( broadcast ) + NSString* token = [[[[deviceToken description] + stringByReplacingOccurrencesOfString:@"<" withString:@""] + stringByReplacingOccurrencesOfString:@">" withString:@""] + stringByReplacingOccurrencesOfString:@" " withString:@""]; + + [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotification object:token]; + } + + - (void) application:(UIApplication*)application + didFailToRegisterForRemoteNotificationsWithError:(NSError*)error + { + // re-post ( broadcast ) + [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotificationError object:error]; + } +#endif + +- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window +{ + // 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]; +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.h b/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.h new file mode 100644 index 00000000..e17e798a --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/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 +// HelloCordova +// +// 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 +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.m b/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.m new file mode 100644 index 00000000..2fe5fc4b --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.m @@ -0,0 +1,164 @@ +/* + 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 +// HelloCordova +// +// 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; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation +{ + // Return YES for supported orientations + return [super shouldAutorotateToInterfaceOrientation:interfaceOrientation]; +} + +/* Comment out the block below to over-ride */ + +/* +- (UIWebView*) newCordovaViewWithFrame:(CGRect)bounds +{ + return[super newCordovaViewWithFrame:bounds]; +} +*/ + +#pragma mark UIWebDelegate implementation + +- (void)webViewDidFinishLoad:(UIWebView*)theWebView +{ + // Black base color for background matches the native apps + theWebView.backgroundColor = [UIColor blackColor]; + + return [super webViewDidFinishLoad:theWebView]; +} + +/* Comment out the block below to over-ride */ + +/* + +- (void) webViewDidStartLoad:(UIWebView*)theWebView +{ + return [super webViewDidStartLoad:theWebView]; +} + +- (void) webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error +{ + return [super webView:theWebView didFailLoadWithError:error]; +} + +- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType +{ + return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType]; +} +*/ + +@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]; +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.xib b/StoneIsland/platforms/ios/StoneIsland/Classes/MainViewController.xib new file mode 100644 index 00000000..e45d65c6 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/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/StoneIsland/platforms/ios/StoneIsland/Plugins/README b/StoneIsland/platforms/ios/StoneIsland/Plugins/README new file mode 100644 index 00000000..87df09f2 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/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/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/IonicKeyboard.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/IonicKeyboard.h new file mode 100644 index 00000000..b54f430d --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/IonicKeyboard.h @@ -0,0 +1,13 @@ +#import <Cordova/CDVPlugin.h> + +@interface IonicKeyboard : CDVPlugin <UIScrollViewDelegate> { + @protected + id _keyboardShowObserver, _keyboardHideObserver; +} + +@property (readwrite, assign) BOOL hideKeyboardAccessoryBar; +@property (readwrite, assign) BOOL disableScroll; +//@property (readwrite, assign) BOOL styleDark; + +@end + diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/IonicKeyboard.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/IonicKeyboard.m new file mode 100644 index 00000000..045cc65f --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/IonicKeyboard.m @@ -0,0 +1,160 @@ +#import "IonicKeyboard.h" +#import "UIWebViewExtension.h" +#import <Cordova/CDVAvailability.h> + +@implementation IonicKeyboard + +@synthesize hideKeyboardAccessoryBar = _hideKeyboardAccessoryBar; +@synthesize disableScroll = _disableScroll; +//@synthesize styleDark = _styleDark; + +- (void)pluginInitialize { + + NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; + __weak IonicKeyboard* weakSelf = self; + + //set defaults + self.hideKeyboardAccessoryBar = NO; + self.disableScroll = NO; + //self.styleDark = NO; + + _keyboardShowObserver = [nc addObserverForName:UIKeyboardWillShowNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* notification) { + + CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; + keyboardFrame = [self.viewController.view convertRect:keyboardFrame fromView:nil]; + + [weakSelf.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.plugins.Keyboard.isVisible = true; cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight': %@ }); ", [@(keyboardFrame.size.height) stringValue]]]; + + //deprecated + [weakSelf.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight': %@ }); ", [@(keyboardFrame.size.height) stringValue]]]; + }]; + + _keyboardHideObserver = [nc addObserverForName:UIKeyboardWillHideNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* notification) { + [weakSelf.commandDelegate evalJs:@"cordova.plugins.Keyboard.isVisible = false; cordova.fireWindowEvent('native.keyboardhide'); "]; + + //deprecated + [weakSelf.commandDelegate evalJs:@"cordova.fireWindowEvent('native.hidekeyboard'); "]; + }]; +} +- (BOOL)disableScroll { + return _disableScroll; +} + +- (void)setDisableScroll:(BOOL)disableScroll { + if (disableScroll == _disableScroll) { + return; + } + if (disableScroll) { + self.webView.scrollView.scrollEnabled = NO; + self.webView.scrollView.delegate = self; + } + else { + self.webView.scrollView.scrollEnabled = YES; + self.webView.scrollView.delegate = nil; + } + + _disableScroll = disableScroll; +} + + +- (BOOL)hideKeyboardAccessoryBar { + return _hideKeyboardAccessoryBar; +} + +- (void)setHideKeyboardAccessoryBar:(BOOL)hideKeyboardAccessoryBar { + if (hideKeyboardAccessoryBar == _hideKeyboardAccessoryBar) { + return; + } + if (hideKeyboardAccessoryBar) { + self.webView.hackishlyHidesInputAccessoryView = YES; + } + else { + self.webView.hackishlyHidesInputAccessoryView = NO; + } + + _hideKeyboardAccessoryBar = hideKeyboardAccessoryBar; +} + +/* +- (BOOL)styleDark { + return _styleDark; +} + +- (void)setStyleDark:(BOOL)styleDark { + if (styleDark == _styleDark) { + return; + } + if (styleDark) { + self.webView.styleDark = YES; + } + else { + self.webView.styleDark = NO; + } + + _styleDark = styleDark; +} +*/ + + +/* ------------------------------------------------------------- */ + +- (void)scrollViewDidScroll:(UIScrollView *)scrollView { + [scrollView setContentOffset: CGPointZero]; +} + +/* ------------------------------------------------------------- */ + +- (void)dealloc { + NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; + + [nc removeObserver:self name:UIKeyboardWillShowNotification object:nil]; + [nc removeObserver:self name:UIKeyboardWillHideNotification object:nil]; +} + +/* ------------------------------------------------------------- */ + +- (void) disableScroll:(CDVInvokedUrlCommand*)command { + if (!command.arguments || ![command.arguments count]){ + return; + } + id value = [command.arguments objectAtIndex:0]; + + self.disableScroll = [value boolValue]; +} + +- (void) hideKeyboardAccessoryBar:(CDVInvokedUrlCommand*)command { + if (!command.arguments || ![command.arguments count]){ + return; + } + id value = [command.arguments objectAtIndex:0]; + + self.hideKeyboardAccessoryBar = [value boolValue]; +} + +- (void) close:(CDVInvokedUrlCommand*)command { + [self.webView endEditing:YES]; +} + +- (void) show:(CDVInvokedUrlCommand*)command { + NSLog(@"Showing keyboard not supported in iOS due to platform limitations."); +} + +/* +- (void) styleDark:(CDVInvokedUrlCommand*)command { + if (!command.arguments || ![command.arguments count]){ + return; + } + id value = [command.arguments objectAtIndex:0]; + + self.styleDark = [value boolValue]; +} +*/ + +@end + diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/UIWebViewExtension.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/UIWebViewExtension.h new file mode 100644 index 00000000..1d6c293d --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/UIWebViewExtension.h @@ -0,0 +1,4 @@ +@interface UIWebView (HackishAccessoryHiding) +@property (nonatomic, assign) BOOL hackishlyHidesInputAccessoryView; +//@property (nonatomic, assign) BOOL styleDark; +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/UIWebViewExtension.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/UIWebViewExtension.m new file mode 100644 index 00000000..25403e6f --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/com.ionic.keyboard/UIWebViewExtension.m @@ -0,0 +1,109 @@ +#import <objc/runtime.h> +#import <UIKit/UIKit.h> +#import "UIWebViewExtension.h" + +//Credit: https://gist.github.com/bjhomer/2048571 +//Also: http://stackoverflow.com/a/23398487/1091751 +@implementation UIWebView (HackishAccessoryHiding) + +static const char * const hackishFixClassName = "UIWebBrowserViewMinusAccessoryView"; +static Class hackishFixClass = Nil; + +- (UIView *)hackishlyFoundBrowserView { + UIScrollView *scrollView = self.scrollView; + + UIView *browserView = nil; + for (UIView *subview in scrollView.subviews) { + if ([NSStringFromClass([subview class]) hasPrefix:@"UIWebBrowserView"]) { + browserView = subview; + break; + } + } + return browserView; +} + +- (id)methodReturningNil { + return nil; +} + +- (void)ensureHackishSubclassExistsOfBrowserViewClass:(Class)browserViewClass { + if (!hackishFixClass) { + Class newClass = objc_allocateClassPair(browserViewClass, hackishFixClassName, 0); + IMP nilImp = [self methodForSelector:@selector(methodReturningNil)]; + class_addMethod(newClass, @selector(inputAccessoryView), nilImp, "@@:"); + objc_registerClassPair(newClass); + + hackishFixClass = newClass; + } +} + +- (BOOL) hackishlyHidesInputAccessoryView { + UIView *browserView = [self hackishlyFoundBrowserView]; + return [browserView class] == hackishFixClass; +} + +- (void) setHackishlyHidesInputAccessoryView:(BOOL)value { + UIView *browserView = [self hackishlyFoundBrowserView]; + if (browserView == nil) { + return; + } + [self ensureHackishSubclassExistsOfBrowserViewClass:[browserView class]]; + + if (value) { + object_setClass(browserView, hackishFixClass); + } + else { + Class normalClass = objc_getClass("UIWebBrowserView"); + object_setClass(browserView, normalClass); + } + [browserView reloadInputViews]; +} +/* ---------------------------------------------------------------- */ + +/* +- (UIKeyboardAppearance) darkKeyboardAppearanceTemplateMethod { + return UIKeyboardAppearanceDark; +} + +- (UIKeyboardAppearance) lightKeyboardAppearanceTemplateMethod { + return UIKeyboardAppearanceLight; +} + +- (BOOL) styleDark { + UIView *browserView = [self hackishlyFoundBrowserView]; + if (browserView == nil) { + return false; + } + + Method m = class_getInstanceMethod( [self class], @selector( darkKeyboardAppearanceTemplateMethod ) ); + IMP imp = method_getImplementation( m ); + + Method m2 = class_getInstanceMethod( [browserView class], @selector(keyboardAppearance) ); + IMP imp2 = method_getImplementation( m2 ); + + return imp == imp2; +} + +- (void) setStyleDark:(BOOL)styleDark { + UIView *browserView = [self hackishlyFoundBrowserView]; + if (browserView == nil) { + return; + } + + if ( styleDark ) { + Method m = class_getInstanceMethod( [self class], @selector( darkKeyboardAppearanceTemplateMethod ) ); + IMP imp = method_getImplementation( m ); + const char* typeEncoding = method_getTypeEncoding( m ); + class_replaceMethod( [browserView class], @selector(keyboardAppearance), imp, typeEncoding ); + } + else { + Method m = class_getInstanceMethod( [self class], @selector( lightKeyboardAppearanceTemplateMethod ) ); + IMP imp = method_getImplementation( m ); + const char* typeEncoding = method_getTypeEncoding( m ); + class_replaceMethod( [browserView class], @selector(keyboardAppearance), imp, typeEncoding ); + } +} +*/ + +@end + diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-console/CDVLogger.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-console/CDVLogger.h new file mode 100644 index 00000000..7cfb3063 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-console/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; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-console/CDVLogger.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-console/CDVLogger.m new file mode 100644 index 00000000..ccfa3a51 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-console/CDVLogger.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 "CDVLogger.h" +#import <Cordova/CDV.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); + } +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-device/CDVDevice.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-device/CDVDevice.h new file mode 100644 index 00000000..a146d882 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/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; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-device/CDVDevice.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-device/CDVDevice.m new file mode 100644 index 00000000..5a3f4708 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-device/CDVDevice.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. + */ + +#include <sys/types.h> +#include <sys/sysctl.h> + +#import <Cordova/CDV.h> +#import "CDVDevice.h" + +@implementation UIDevice (ModelVersion) + +- (NSString*)modelVersion +{ + 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); + + return platform; +} + +@end + +@interface CDVDevice () {} +@end + +@implementation CDVDevice + +- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device +{ + NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; + static NSString* UUID_KEY = @"CDVUUID"; + + NSString* app_uuid = [userDefaults stringForKey:UUID_KEY]; + + if (app_uuid == nil) { + CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); + CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); + + app_uuid = [NSString stringWithString:(__bridge NSString*)uuidString]; + [userDefaults setObject:app_uuid forKey:UUID_KEY]; + [userDefaults synchronize]; + + CFRelease(uuidString); + CFRelease(uuidRef); + } + + return app_uuid; +} + +- (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]; + NSMutableDictionary* devProps = [NSMutableDictionary dictionaryWithCapacity:4]; + + [devProps setObject:@"Apple" forKey:@"manufacturer"]; + [devProps setObject:[device modelVersion] forKey:@"model"]; + [devProps setObject:@"iOS" forKey:@"platform"]; + [devProps setObject:[device systemVersion] forKey:@"version"]; + [devProps setObject:[self uniqueAppInstanceIdentifier:device] forKey:@"uuid"]; + [devProps setObject:[[self class] cordovaVersion] forKey:@"cordova"]; + + NSDictionary* devReturn = [NSDictionary dictionaryWithDictionary:devProps]; + return devReturn; +} + ++ (NSString*)cordovaVersion +{ + return CDV_VERSION; +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-dialogs/CDVNotification.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-dialogs/CDVNotification.h new file mode 100644 index 00000000..9253f6a9 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-dialogs/CDVNotification.h @@ -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 <Foundation/Foundation.h> +#import <UIKit/UIKit.h> +#import <AudioToolbox/AudioServices.h> +#import <Cordova/CDVPlugin.h> + +@interface CDVNotification : CDVPlugin <UIAlertViewDelegate>{} + +- (void)alert:(CDVInvokedUrlCommand*)command; +- (void)confirm:(CDVInvokedUrlCommand*)command; +- (void)prompt:(CDVInvokedUrlCommand*)command; +- (void)beep:(CDVInvokedUrlCommand*)command; + +@end + +@interface CDVAlertView : UIAlertView {} +@property (nonatomic, copy) NSString* callbackId; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-dialogs/CDVNotification.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-dialogs/CDVNotification.m new file mode 100644 index 00000000..1581ad3c --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-dialogs/CDVNotification.m @@ -0,0 +1,221 @@ +/* + 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 "CDVNotification.h" + +#define DIALOG_TYPE_ALERT @"alert" +#define DIALOG_TYPE_PROMPT @"prompt" + +static void soundCompletionCallback(SystemSoundID ssid, void* data); + +@implementation CDVNotification + +/* + * showDialogWithMessage - Common method to instantiate the alert view for alert, confirm, and prompt notifications. + * Parameters: + * message The alert view message. + * title The alert view title. + * buttons The array of customized strings for the buttons. + * defaultText The input text for the textbox (if textbox exists). + * callbackId The commmand callback id. + * dialogType The type of alert view [alert | prompt]. + */ +- (void)showDialogWithMessage:(NSString*)message title:(NSString*)title buttons:(NSArray*)buttons defaultText:(NSString*)defaultText callbackId:(NSString*)callbackId dialogType:(NSString*)dialogType +{ + + NSUInteger count = [buttons count]; +#ifdef __IPHONE_8_0 + if (NSClassFromString(@"UIAlertController")) { + + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; + + if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.3) { + + CGRect alertFrame = [UIScreen mainScreen].applicationFrame; + + if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) { + // swap the values for the app frame since it is now in landscape + CGFloat temp = alertFrame.size.width; + alertFrame.size.width = alertFrame.size.height; + alertFrame.size.height = temp; + } + + alertController.view.frame = alertFrame; + } + + for (int n = 0; n < count; n++) { + + UIAlertAction* action = [UIAlertAction actionWithTitle:[buttons objectAtIndex:n] style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) + { + CDVPluginResult* result; + + if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) { + + NSString* value0 = [[alertController.textFields objectAtIndex:0] text]; + NSDictionary* info = @{ + @"buttonIndex":@(n + 1), + @"input1":(value0 ? value0 : [NSNull null]) + }; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:info]; + + } else { + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)(n + 1)]; + + } + + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + + }]; + [alertController addAction:action]; + + } + + if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) { + + [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) { + textField.text = defaultText; + }]; + } + + + + [self.viewController presentViewController:alertController animated:YES completion:nil]; + + } else { +#endif + CDVAlertView* alertView = [[CDVAlertView alloc] + initWithTitle:title + message:message + delegate:self + cancelButtonTitle:nil + otherButtonTitles:nil]; + + alertView.callbackId = callbackId; + + + + for (int n = 0; n < count; n++) { + [alertView addButtonWithTitle:[buttons objectAtIndex:n]]; + } + + if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) { + alertView.alertViewStyle = UIAlertViewStylePlainTextInput; + UITextField* textField = [alertView textFieldAtIndex:0]; + textField.text = defaultText; + } + + [alertView show]; +#ifdef __IPHONE_8_0 + } +#endif + +} + +- (void)alert:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* message = [command argumentAtIndex:0]; + NSString* title = [command argumentAtIndex:1]; + NSString* buttons = [command argumentAtIndex:2]; + + [self showDialogWithMessage:message title:title buttons:@[buttons] defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT]; +} + +- (void)confirm:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* message = [command argumentAtIndex:0]; + NSString* title = [command argumentAtIndex:1]; + NSArray* buttons = [command argumentAtIndex:2]; + + [self showDialogWithMessage:message title:title buttons:buttons defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT]; +} + +- (void)prompt:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* message = [command argumentAtIndex:0]; + NSString* title = [command argumentAtIndex:1]; + NSArray* buttons = [command argumentAtIndex:2]; + NSString* defaultText = [command argumentAtIndex:3]; + + [self showDialogWithMessage:message title:title buttons:buttons defaultText:defaultText callbackId:callbackId dialogType:DIALOG_TYPE_PROMPT]; +} + +/** + * Callback invoked when an alert dialog's buttons are clicked. + */ +- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex +{ + CDVAlertView* cdvAlertView = (CDVAlertView*)alertView; + CDVPluginResult* result; + + // Determine what gets returned to JS based on the alert view type. + if (alertView.alertViewStyle == UIAlertViewStyleDefault) { + // For alert and confirm, return button index as int back to JS. + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)(buttonIndex + 1)]; + } else { + // For prompt, return button index and input text back to JS. + NSString* value0 = [[alertView textFieldAtIndex:0] text]; + NSDictionary* info = @{ + @"buttonIndex":@(buttonIndex + 1), + @"input1":(value0 ? value0 : [NSNull null]) + }; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:info]; + } + [self.commandDelegate sendPluginResult:result callbackId:cdvAlertView.callbackId]; +} + +static void playBeep(int count) { + SystemSoundID completeSound; + NSInteger cbDataCount = count; + NSURL* audioPath = [[NSBundle mainBundle] URLForResource:@"CDVNotification.bundle/beep" withExtension:@"wav"]; + #if __has_feature(objc_arc) + AudioServicesCreateSystemSoundID((__bridge CFURLRef)audioPath, &completeSound); + #else + AudioServicesCreateSystemSoundID((CFURLRef)audioPath, &completeSound); + #endif + AudioServicesAddSystemSoundCompletion(completeSound, NULL, NULL, soundCompletionCallback, (void*)(cbDataCount-1)); + AudioServicesPlaySystemSound(completeSound); +} + +static void soundCompletionCallback(SystemSoundID ssid, void* data) { + int count = (int)data; + AudioServicesRemoveSystemSoundCompletion (ssid); + AudioServicesDisposeSystemSoundID(ssid); + if (count > 0) { + playBeep(count); + } +} + +- (void)beep:(CDVInvokedUrlCommand*)command +{ + NSNumber* count = [command argumentAtIndex:0 withDefault:[NSNumber numberWithInt:1]]; + playBeep([count intValue]); +} + + +@end + +@implementation CDVAlertView + +@synthesize callbackId; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-geolocation/CDVLocation.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-geolocation/CDVLocation.h new file mode 100644 index 00000000..cce2738f --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-geolocation/CDVLocation.h @@ -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 <UIKit/UIKit.h> +#import <CoreLocation/CoreLocation.h> +#import <Cordova/CDVPlugin.h> + +enum CDVLocationStatus { + PERMISSIONDENIED = 1, + POSITIONUNAVAILABLE, + TIMEOUT +}; +typedef NSUInteger CDVLocationStatus; + +// simple object to keep track of location information +@interface CDVLocationData : NSObject { + CDVLocationStatus locationStatus; + NSMutableArray* locationCallbacks; + NSMutableDictionary* watchCallbacks; + CLLocation* locationInfo; +} + +@property (nonatomic, assign) CDVLocationStatus locationStatus; +@property (nonatomic, strong) CLLocation* locationInfo; +@property (nonatomic, strong) NSMutableArray* locationCallbacks; +@property (nonatomic, strong) NSMutableDictionary* watchCallbacks; + +@end + +@interface CDVLocation : CDVPlugin <CLLocationManagerDelegate>{ + @private BOOL __locationStarted; + @private BOOL __highAccuracyEnabled; + CDVLocationData* locationData; +} + +@property (nonatomic, strong) CLLocationManager* locationManager; +@property (nonatomic, strong) CDVLocationData* locationData; + +- (void)getLocation:(CDVInvokedUrlCommand*)command; +- (void)addWatch:(CDVInvokedUrlCommand*)command; +- (void)clearWatch:(CDVInvokedUrlCommand*)command; +- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback; +- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message; +- (void)startLocation:(BOOL)enableHighAccuracy; + +- (void)locationManager:(CLLocationManager*)manager + didUpdateToLocation:(CLLocation*)newLocation + fromLocation:(CLLocation*)oldLocation; + +- (void)locationManager:(CLLocationManager*)manager + didFailWithError:(NSError*)error; + +- (BOOL)isLocationServicesEnabled; +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-geolocation/CDVLocation.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-geolocation/CDVLocation.m new file mode 100644 index 00000000..8b543c8e --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-geolocation/CDVLocation.m @@ -0,0 +1,366 @@ +/* + 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 "CDVLocation.h" + +#pragma mark Constants + +#define kPGLocationErrorDomain @"kPGLocationErrorDomain" +#define kPGLocationDesiredAccuracyKey @"desiredAccuracy" +#define kPGLocationForcePromptKey @"forcePrompt" +#define kPGLocationDistanceFilterKey @"distanceFilter" +#define kPGLocationFrequencyKey @"frequency" + +#pragma mark - +#pragma mark Categories + +@implementation CDVLocationData + +@synthesize locationStatus, locationInfo, locationCallbacks, watchCallbacks; +- (CDVLocationData*)init +{ + self = (CDVLocationData*)[super init]; + if (self) { + self.locationInfo = nil; + self.locationCallbacks = nil; + self.watchCallbacks = nil; + } + return self; +} + +@end + +#pragma mark - +#pragma mark CDVLocation + +@implementation CDVLocation + +@synthesize locationManager, locationData; + +- (void)pluginInitialize +{ + self.locationManager = [[CLLocationManager alloc] init]; + self.locationManager.delegate = self; // Tells the location manager to send updates to this object + __locationStarted = NO; + __highAccuracyEnabled = NO; + self.locationData = nil; +} + +- (BOOL)isAuthorized +{ + BOOL authorizationStatusClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+ + + if (authorizationStatusClassPropertyAvailable) { + NSUInteger authStatus = [CLLocationManager authorizationStatus]; +#ifdef __IPHONE_8_0 + if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { //iOS 8.0+ + return (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) || (authStatus == kCLAuthorizationStatusAuthorizedAlways) || (authStatus == kCLAuthorizationStatusNotDetermined); + } +#endif + return (authStatus == kCLAuthorizationStatusAuthorized) || (authStatus == kCLAuthorizationStatusNotDetermined); + } + + // by default, assume YES (for iOS < 4.2) + return YES; +} + +- (BOOL)isLocationServicesEnabled +{ + BOOL locationServicesEnabledInstancePropertyAvailable = [self.locationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 3.x + BOOL locationServicesEnabledClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 4.x + + if (locationServicesEnabledClassPropertyAvailable) { // iOS 4.x + return [CLLocationManager locationServicesEnabled]; + } else if (locationServicesEnabledInstancePropertyAvailable) { // iOS 2.x, iOS 3.x + return [(id)self.locationManager locationServicesEnabled]; + } else { + return NO; + } +} + +- (void)startLocation:(BOOL)enableHighAccuracy +{ + if (![self isLocationServicesEnabled]) { + [self returnLocationError:PERMISSIONDENIED withMessage:@"Location services are not enabled."]; + return; + } + if (![self isAuthorized]) { + NSString* message = nil; + BOOL authStatusAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+ + if (authStatusAvailable) { + NSUInteger code = [CLLocationManager authorizationStatus]; + if (code == kCLAuthorizationStatusNotDetermined) { + // could return POSITION_UNAVAILABLE but need to coordinate with other platforms + message = @"User undecided on application's use of location services."; + } else if (code == kCLAuthorizationStatusRestricted) { + message = @"Application's use of location services is restricted."; + } + } + // PERMISSIONDENIED is only PositionError that makes sense when authorization denied + [self returnLocationError:PERMISSIONDENIED withMessage:message]; + + return; + } + +#ifdef __IPHONE_8_0 + NSUInteger code = [CLLocationManager authorizationStatus]; + if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) { //iOS8+ + __highAccuracyEnabled = enableHighAccuracy; + if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){ + [self.locationManager requestAlwaysAuthorization]; + } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) { + [self.locationManager requestWhenInUseAuthorization]; + } else { + NSLog(@"[Warning] No NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key is defined in the Info.plist file."); + } + return; + } +#endif + + // Tell the location manager to start notifying us of location updates. We + // first stop, and then start the updating to ensure we get at least one + // update, even if our location did not change. + [self.locationManager stopUpdatingLocation]; + [self.locationManager startUpdatingLocation]; + __locationStarted = YES; + if (enableHighAccuracy) { + __highAccuracyEnabled = YES; + // Set distance filter to 5 for a high accuracy. Setting it to "kCLDistanceFilterNone" could provide a + // higher accuracy, but it's also just spamming the callback with useless reports which drain the battery. + self.locationManager.distanceFilter = 5; + // Set desired accuracy to Best. + self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; + } else { + __highAccuracyEnabled = NO; + // TODO: Set distance filter to 10 meters? and desired accuracy to nearest ten meters? arbitrary. + self.locationManager.distanceFilter = 10; + self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; + } +} + +- (void)_stopLocation +{ + if (__locationStarted) { + if (![self isLocationServicesEnabled]) { + return; + } + + [self.locationManager stopUpdatingLocation]; + __locationStarted = NO; + __highAccuracyEnabled = NO; + } +} + +- (void)locationManager:(CLLocationManager*)manager + didUpdateToLocation:(CLLocation*)newLocation + fromLocation:(CLLocation*)oldLocation +{ + CDVLocationData* cData = self.locationData; + + cData.locationInfo = newLocation; + if (self.locationData.locationCallbacks.count > 0) { + for (NSString* callbackId in self.locationData.locationCallbacks) { + [self returnLocationInfo:callbackId andKeepCallback:NO]; + } + + [self.locationData.locationCallbacks removeAllObjects]; + } + if (self.locationData.watchCallbacks.count > 0) { + for (NSString* timerId in self.locationData.watchCallbacks) { + [self returnLocationInfo:[self.locationData.watchCallbacks objectForKey:timerId] andKeepCallback:YES]; + } + } else { + // No callbacks waiting on us anymore, turn off listening. + [self _stopLocation]; + } +} + +- (void)getLocation:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + BOOL enableHighAccuracy = [[command argumentAtIndex:0] boolValue]; + + if ([self isLocationServicesEnabled] == NO) { + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"]; + [posError setObject:@"Location services are disabled." forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } else { + if (!self.locationData) { + self.locationData = [[CDVLocationData alloc] init]; + } + CDVLocationData* lData = self.locationData; + if (!lData.locationCallbacks) { + lData.locationCallbacks = [NSMutableArray arrayWithCapacity:1]; + } + + if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) { + // add the callbackId into the array so we can call back when get data + if (callbackId != nil) { + [lData.locationCallbacks addObject:callbackId]; + } + // Tell the location manager to start notifying us of heading updates + [self startLocation:enableHighAccuracy]; + } else { + [self returnLocationInfo:callbackId andKeepCallback:NO]; + } + } +} + +- (void)addWatch:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* timerId = [command argumentAtIndex:0]; + BOOL enableHighAccuracy = [[command argumentAtIndex:1] boolValue]; + + if (!self.locationData) { + self.locationData = [[CDVLocationData alloc] init]; + } + CDVLocationData* lData = self.locationData; + + if (!lData.watchCallbacks) { + lData.watchCallbacks = [NSMutableDictionary dictionaryWithCapacity:1]; + } + + // add the callbackId into the dictionary so we can call back whenever get data + [lData.watchCallbacks setObject:callbackId forKey:timerId]; + + if ([self isLocationServicesEnabled] == NO) { + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"]; + [posError setObject:@"Location services are disabled." forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } else { + if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) { + // Tell the location manager to start notifying us of location updates + [self startLocation:enableHighAccuracy]; + } + } +} + +- (void)clearWatch:(CDVInvokedUrlCommand*)command +{ + NSString* timerId = [command argumentAtIndex:0]; + + if (self.locationData && self.locationData.watchCallbacks && [self.locationData.watchCallbacks objectForKey:timerId]) { + [self.locationData.watchCallbacks removeObjectForKey:timerId]; + if([self.locationData.watchCallbacks count] == 0) { + [self _stopLocation]; + } + } +} + +- (void)stopLocation:(CDVInvokedUrlCommand*)command +{ + [self _stopLocation]; +} + +- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback +{ + CDVPluginResult* result = nil; + CDVLocationData* lData = self.locationData; + + if (lData && !lData.locationInfo) { + // return error + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:POSITIONUNAVAILABLE]; + } else if (lData && lData.locationInfo) { + CLLocation* lInfo = lData.locationInfo; + NSMutableDictionary* returnInfo = [NSMutableDictionary dictionaryWithCapacity:8]; + NSNumber* timestamp = [NSNumber numberWithDouble:([lInfo.timestamp timeIntervalSince1970] * 1000)]; + [returnInfo setObject:timestamp forKey:@"timestamp"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.speed] forKey:@"velocity"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.verticalAccuracy] forKey:@"altitudeAccuracy"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.horizontalAccuracy] forKey:@"accuracy"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.course] forKey:@"heading"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.altitude] forKey:@"altitude"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.latitude] forKey:@"latitude"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.longitude] forKey:@"longitude"]; + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:returnInfo]; + [result setKeepCallbackAsBool:keepCallback]; + } + if (result) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } +} + +- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message +{ + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + + [posError setObject:[NSNumber numberWithUnsignedInteger:errorCode] forKey:@"code"]; + [posError setObject:message ? message:@"" forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + + for (NSString* callbackId in self.locationData.locationCallbacks) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } + + [self.locationData.locationCallbacks removeAllObjects]; + + for (NSString* callbackId in self.locationData.watchCallbacks) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } +} + +- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error +{ + NSLog(@"locationManager::didFailWithError %@", [error localizedFailureReason]); + + CDVLocationData* lData = self.locationData; + if (lData && __locationStarted) { + // TODO: probably have to once over the various error codes and return one of: + // PositionError.PERMISSION_DENIED = 1; + // PositionError.POSITION_UNAVAILABLE = 2; + // PositionError.TIMEOUT = 3; + NSUInteger positionError = POSITIONUNAVAILABLE; + if (error.code == kCLErrorDenied) { + positionError = PERMISSIONDENIED; + } + [self returnLocationError:positionError withMessage:[error localizedDescription]]; + } + + if (error.code != kCLErrorLocationUnknown) { + [self.locationManager stopUpdatingLocation]; + __locationStarted = NO; + } +} + +//iOS8+ +-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status +{ + if(!__locationStarted){ + [self startLocation:__highAccuracyEnabled]; + } +} + +- (void)dealloc +{ + self.locationManager.delegate = nil; +} + +- (void)onReset +{ + [self _stopLocation]; + [self.locationManager stopUpdatingHeading]; +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVConnection.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVConnection.h new file mode 100644 index 00000000..8add0279 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVConnection.h @@ -0,0 +1,34 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import <Foundation/Foundation.h> +#import <Cordova/CDVPlugin.h> +#import "CDVReachability.h" + +@interface CDVConnection : CDVPlugin { + NSString* type; + NSString* _callbackId; + + CDVReachability* internetReach; +} + +@property (copy) NSString* connectionType; +@property (strong) CDVReachability* internetReach; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVConnection.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVConnection.m new file mode 100644 index 00000000..37497675 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVConnection.m @@ -0,0 +1,127 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVConnection.h" +#import "CDVReachability.h" + +@interface CDVConnection (PrivateMethods) +- (void)updateOnlineStatus; +- (void)sendPluginResult; +@end + +@implementation CDVConnection + +@synthesize connectionType, internetReach; + +- (void)getConnectionInfo:(CDVInvokedUrlCommand*)command +{ + _callbackId = command.callbackId; + [self sendPluginResult]; +} + +- (void)sendPluginResult +{ + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType]; + + [result setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:result callbackId:_callbackId]; +} + +- (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability +{ + NetworkStatus networkStatus = [reachability currentReachabilityStatus]; + + switch (networkStatus) { + case NotReachable: + return @"none"; + + case ReachableViaWWAN: + { + BOOL isConnectionRequired = [reachability connectionRequired]; + if (isConnectionRequired) { + return @"none"; + } else { + return @"cellular"; + } + } + case ReachableViaWiFi: + return @"wifi"; + + default: + return @"unknown"; + } +} + +- (BOOL)isCellularConnection:(NSString*)theConnectionType +{ + return [theConnectionType isEqualToString:@"2g"] || + [theConnectionType isEqualToString:@"3g"] || + [theConnectionType isEqualToString:@"4g"] || + [theConnectionType isEqualToString:@"cellular"]; +} + +- (void)updateReachability:(CDVReachability*)reachability +{ + if (reachability) { + // check whether the connection type has changed + NSString* newConnectionType = [self w3cConnectionTypeFor:reachability]; + if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes + return; + } else { + self.connectionType = [self w3cConnectionTypeFor:reachability]; + } + } + [self sendPluginResult]; +} + +- (void)updateConnectionType:(NSNotification*)note +{ + CDVReachability* curReach = [note object]; + + if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) { + [self updateReachability:curReach]; + } +} + +- (void)onPause +{ + [self.internetReach stopNotifier]; +} + +- (void)onResume +{ + [self.internetReach startNotifier]; + [self updateReachability:self.internetReach]; +} + +- (void)pluginInitialize +{ + self.connectionType = @"none"; + self.internetReach = [CDVReachability reachabilityForInternetConnection]; + self.connectionType = [self w3cConnectionTypeFor:self.internetReach]; + [self.internetReach startNotifier]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) + name:kReachabilityChangedNotification object:nil]; + if (&UIApplicationDidEnterBackgroundNotification && &UIApplicationWillEnterForegroundNotification) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; + } +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVReachability.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVReachability.h new file mode 100644 index 00000000..01a95c35 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVReachability.h @@ -0,0 +1,85 @@ +/* + + File: Reachability.h + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import <Foundation/Foundation.h> +#import <SystemConfiguration/SystemConfiguration.h> +#import <netinet/in.h> + +typedef enum { + NotReachable = 0, + ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons + ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons +} NetworkStatus; +#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" + +@interface CDVReachability : NSObject +{ + BOOL localWiFiRef; + SCNetworkReachabilityRef reachabilityRef; +} + +// reachabilityWithHostName- Use to check the reachability of a particular host name. ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; + +// reachabilityWithAddress- Use to check the reachability of a particular IP address. ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; + +// reachabilityForInternetConnection- checks whether the default route is available. +// Should be used by applications that do not connect to a particular host ++ (CDVReachability*)reachabilityForInternetConnection; + +// reachabilityForLocalWiFi- checks whether a local wifi connection is available. ++ (CDVReachability*)reachabilityForLocalWiFi; + +// Start listening for reachability notifications on the current run loop +- (BOOL)startNotifier; +- (void)stopNotifier; + +- (NetworkStatus)currentReachabilityStatus; +// WWAN may be available, but not active until a connection has been established. +// WiFi may require a connection for VPN on Demand. +- (BOOL)connectionRequired; +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVReachability.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVReachability.m new file mode 100644 index 00000000..c60261ae --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-network-information/CDVReachability.m @@ -0,0 +1,260 @@ +/* + + File: Reachability.m + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import <sys/socket.h> +#import <netinet/in.h> +#import <netinet6/in6.h> +#import <arpa/inet.h> +#import <ifaddrs.h> +#import <netdb.h> + +#import <CoreFoundation/CoreFoundation.h> + +#import "CDVReachability.h" + +#define kShouldPrintReachabilityFlags 0 + +static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) +{ +#if kShouldPrintReachabilityFlags + NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", + (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', + (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', + + (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', + (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', + (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', + (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', + comment + ); +#endif +} + +@implementation CDVReachability + +static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) +{ +#pragma unused (target, flags) + // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); + // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); + + // Converted the asserts above to conditionals, with safe return from the function + if (info == NULL) { + NSLog(@"info was NULL in ReachabilityCallback"); + return; + } + + if (![(__bridge NSObject*)info isKindOfClass :[CDVReachability class]]) { + NSLog(@"info was wrong class in ReachabilityCallback"); + return; + } + + // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively + // in case someon uses the Reachability object in a different thread. + @autoreleasepool { + CDVReachability* noteObject = (__bridge CDVReachability*)info; + // Post a notification to notify the client that the network reachability changed. + [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject]; + } +} + +- (BOOL)startNotifier +{ + BOOL retVal = NO; + SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL}; + + if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) { + if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { + retVal = YES; + } + } + return retVal; +} + +- (void)stopNotifier +{ + if (reachabilityRef != NULL) { + SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); + } +} + +- (void)dealloc +{ + [self stopNotifier]; + if (reachabilityRef != NULL) { + CFRelease(reachabilityRef); + } +} + ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; +{ + CDVReachability* retVal = NULL; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + retVal->localWiFiRef = NO; + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; +{ + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); + CDVReachability* retVal = NULL; + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + retVal->localWiFiRef = NO; + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityForInternetConnection; +{ + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; + return [self reachabilityWithAddress:&zeroAddress]; +} + ++ (CDVReachability*)reachabilityForLocalWiFi; +{ + struct sockaddr_in localWifiAddress; + bzero(&localWifiAddress, sizeof(localWifiAddress)); + localWifiAddress.sin_len = sizeof(localWifiAddress); + localWifiAddress.sin_family = AF_INET; + // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 + localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); + CDVReachability* retVal = [self reachabilityWithAddress:&localWifiAddress]; + if (retVal != NULL) { + retVal->localWiFiRef = YES; + } + return retVal; +} + +#pragma mark Network Flag Handling + +- (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "localWiFiStatusForFlags"); + + BOOL retVal = NotReachable; + if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) { + retVal = ReachableViaWiFi; + } + return retVal; +} + +- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "networkStatusForFlags"); + if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { + // if target host is not reachable + return NotReachable; + } + + NetworkStatus retVal = NotReachable; + + if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) { + // if target host is reachable and no connection is required + // then we'll assume (for now) that your on Wi-Fi + retVal = ReachableViaWiFi; + } + + if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) || + ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) { + // ... and the connection is on-demand (or on-traffic) if the + // calling application is using the CFSocketStream or higher APIs + + if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) { + // ... and no [user] intervention is needed + retVal = ReachableViaWiFi; + } + } + + if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) { + // ... but WWAN connections are OK if the calling application + // is using the CFNetwork (CFSocketStream?) APIs. + retVal = ReachableViaWWAN; + } + return retVal; +} + +- (BOOL)connectionRequired; +{ + NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + return flags & kSCNetworkReachabilityFlagsConnectionRequired; + } + return NO; +} + +- (NetworkStatus)currentReachabilityStatus +{ + NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); + NetworkStatus retVal = NotReachable; + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + if (localWiFiRef) { + retVal = [self localWiFiStatusForFlags:flags]; + } else { + retVal = [self networkStatusForFlags:flags]; + } + } + return retVal; +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVSplashScreen.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVSplashScreen.h new file mode 100644 index 00000000..0d6ae397 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVSplashScreen.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. + */ + +#import <Foundation/Foundation.h> +#import <Cordova/CDVPlugin.h> + +typedef struct { + BOOL iPhone; + BOOL iPad; + BOOL iPhone5; + BOOL iPhone6; + BOOL iPhone6Plus; + BOOL retina; + +} CDV_iOSDevice; + +@interface CDVSplashScreen : CDVPlugin { + UIActivityIndicatorView* _activityView; + UIImageView* _imageView; + NSString* _curImageName; + BOOL _visible; +} + +- (void)show:(CDVInvokedUrlCommand*)command; +- (void)hide:(CDVInvokedUrlCommand*)command; + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVSplashScreen.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVSplashScreen.m new file mode 100644 index 00000000..43b356ad --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVSplashScreen.m @@ -0,0 +1,330 @@ +/* + 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 "CDVSplashScreen.h" +#import <Cordova/CDVViewController.h> +#import <Cordova/CDVScreenOrientationDelegate.h> +#import "CDVViewController+SplashScreen.h" + +#define kSplashScreenDurationDefault 0.25f + + +@implementation CDVSplashScreen + +- (void)pluginInitialize +{ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageDidLoad) name:CDVPageDidLoadNotification object:self.webView]; + + [self setVisible:YES]; +} + +- (void)show:(CDVInvokedUrlCommand*)command +{ + [self setVisible:YES]; +} + +- (void)hide:(CDVInvokedUrlCommand*)command +{ + [self setVisible:NO]; +} + +- (void)pageDidLoad +{ + id autoHideSplashScreenValue = [self.commandDelegate.settings objectForKey:[@"AutoHideSplashScreen" lowercaseString]]; + + // if value is missing, default to yes + if ((autoHideSplashScreenValue == nil) || [autoHideSplashScreenValue boolValue]) { + [self setVisible:NO]; + } +} + +- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context +{ + [self updateImage]; +} + +- (void)createViews +{ + /* + * The Activity View is the top spinning throbber in the status/battery bar. We init it with the default Grey Style. + * + * whiteLarge = UIActivityIndicatorViewStyleWhiteLarge + * white = UIActivityIndicatorViewStyleWhite + * gray = UIActivityIndicatorViewStyleGray + * + */ + + // Determine whether rotation should be enabled for this device + // Per iOS HIG, landscape is only supported on iPad and iPhone 6+ + CDV_iOSDevice device = [self getCurrentDevice]; + BOOL autorotateValue = (device.iPad || device.iPhone6Plus) ? + [(CDVViewController *)self.viewController shouldAutorotateDefaultValue] : + NO; + + [(CDVViewController *)self.viewController setEnabledAutorotation:autorotateValue]; + + NSString* topActivityIndicator = [self.commandDelegate.settings objectForKey:[@"TopActivityIndicator" lowercaseString]]; + UIActivityIndicatorViewStyle topActivityIndicatorStyle = UIActivityIndicatorViewStyleGray; + + if ([topActivityIndicator isEqualToString:@"whiteLarge"]) { + topActivityIndicatorStyle = UIActivityIndicatorViewStyleWhiteLarge; + } else if ([topActivityIndicator isEqualToString:@"white"]) { + topActivityIndicatorStyle = UIActivityIndicatorViewStyleWhite; + } else if ([topActivityIndicator isEqualToString:@"gray"]) { + topActivityIndicatorStyle = UIActivityIndicatorViewStyleGray; + } + + UIView* parentView = self.viewController.view; + parentView.userInteractionEnabled = NO; // disable user interaction while splashscreen is shown + _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:topActivityIndicatorStyle]; + _activityView.center = CGPointMake(parentView.bounds.size.width / 2, parentView.bounds.size.height / 2); + _activityView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin + | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin; + [_activityView startAnimating]; + + // Set the frame & image later. + _imageView = [[UIImageView alloc] init]; + [parentView addSubview:_imageView]; + + id showSplashScreenSpinnerValue = [self.commandDelegate.settings objectForKey:[@"ShowSplashScreenSpinner" lowercaseString]]; + // backwards compatibility - if key is missing, default to true + if ((showSplashScreenSpinnerValue == nil) || [showSplashScreenSpinnerValue boolValue]) { + [parentView addSubview:_activityView]; + } + + // Frame is required when launching in portrait mode. + // Bounds for landscape since it captures the rotation. + [parentView addObserver:self forKeyPath:@"frame" options:0 context:nil]; + [parentView addObserver:self forKeyPath:@"bounds" options:0 context:nil]; + + [self updateImage]; +} + +- (void)destroyViews +{ + [(CDVViewController *)self.viewController setEnabledAutorotation:[(CDVViewController *)self.viewController shouldAutorotateDefaultValue]]; + + [_imageView removeFromSuperview]; + [_activityView removeFromSuperview]; + _imageView = nil; + _activityView = nil; + _curImageName = nil; + + self.viewController.view.userInteractionEnabled = YES; // re-enable user interaction upon completion + [self.viewController.view removeObserver:self forKeyPath:@"frame"]; + [self.viewController.view removeObserver:self forKeyPath:@"bounds"]; +} + +- (CDV_iOSDevice) getCurrentDevice +{ + CDV_iOSDevice device; + + UIScreen* mainScreen = [UIScreen mainScreen]; + CGFloat mainScreenHeight = mainScreen.bounds.size.height; + CGFloat mainScreenWidth = mainScreen.bounds.size.width; + + int limit = MAX(mainScreenHeight,mainScreenWidth); + + device.iPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad); + device.iPhone = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone); + device.retina = ([mainScreen scale] == 2.0); + device.iPhone5 = (device.iPhone && limit == 568.0); + // note these below is not a true device detect, for example if you are on an + // iPhone 6/6+ but the app is scaled it will prob set iPhone5 as true, but + // this is appropriate for detecting the runtime screen environment + device.iPhone6 = (device.iPhone && limit == 667.0); + device.iPhone6Plus = (device.iPhone && limit == 736.0); + + return device; +} + +- (NSString*)getImageName:(UIInterfaceOrientation)currentOrientation delegate:(id<CDVScreenOrientationDelegate>)orientationDelegate device:(CDV_iOSDevice)device +{ + // Use UILaunchImageFile if specified in plist. Otherwise, use Default. + NSString* imageName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UILaunchImageFile"]; + + NSUInteger supportedOrientations = [orientationDelegate supportedInterfaceOrientations]; + + // Checks to see if the developer has locked the orientation to use only one of Portrait or Landscape + BOOL supportsLandscape = (supportedOrientations & UIInterfaceOrientationMaskLandscape); + BOOL supportsPortrait = (supportedOrientations & UIInterfaceOrientationMaskPortrait || supportedOrientations & UIInterfaceOrientationMaskPortraitUpsideDown); + // this means there are no mixed orientations in there + BOOL isOrientationLocked = !(supportsPortrait && supportsLandscape); + + if (imageName) { + imageName = [imageName stringByDeletingPathExtension]; + } else { + imageName = @"Default"; + } + + if (device.iPhone5) { // does not support landscape + imageName = [imageName stringByAppendingString:@"-568h"]; + } else if (device.iPhone6) { // does not support landscape + imageName = [imageName stringByAppendingString:@"-667h"]; + } else if (device.iPhone6Plus) { // supports landscape + if (isOrientationLocked) { + imageName = [imageName stringByAppendingString:(supportsLandscape ? @"-Landscape" : @"")]; + } else { + switch (currentOrientation) { + case UIInterfaceOrientationLandscapeLeft: + case UIInterfaceOrientationLandscapeRight: + imageName = [imageName stringByAppendingString:@"-Landscape"]; + break; + default: + break; + } + } + imageName = [imageName stringByAppendingString:@"-736h"]; + + } else if (device.iPad) { // supports landscape + if (isOrientationLocked) { + imageName = [imageName stringByAppendingString:(supportsLandscape ? @"-Landscape" : @"-Portrait")]; + } else { + switch (currentOrientation) { + case UIInterfaceOrientationLandscapeLeft: + case UIInterfaceOrientationLandscapeRight: + imageName = [imageName stringByAppendingString:@"-Landscape"]; + break; + + case UIInterfaceOrientationPortrait: + case UIInterfaceOrientationPortraitUpsideDown: + default: + imageName = [imageName stringByAppendingString:@"-Portrait"]; + break; + } + } + } + + return imageName; +} + +// Sets the view's frame and image. +- (void)updateImage +{ + NSString* imageName = [self getImageName:[[UIApplication sharedApplication] statusBarOrientation] delegate:(id<CDVScreenOrientationDelegate>)self.viewController device:[self getCurrentDevice]]; + + if (![imageName isEqualToString:_curImageName]) { + UIImage* img = [UIImage imageNamed:imageName]; + _imageView.image = img; + _curImageName = imageName; + } + + // Check that splash screen's image exists before updating bounds + if (_imageView.image) { + [self updateBounds]; + } else { + NSLog(@"WARNING: The splashscreen image named %@ was not found", imageName); + } +} + +- (void)updateBounds +{ + UIImage* img = _imageView.image; + CGRect imgBounds = (img) ? CGRectMake(0, 0, img.size.width, img.size.height) : CGRectZero; + + CGSize screenSize = [self.viewController.view convertRect:[UIScreen mainScreen].bounds fromView:nil].size; + UIInterfaceOrientation orientation = self.viewController.interfaceOrientation; + CGAffineTransform imgTransform = CGAffineTransformIdentity; + + /* If and only if an iPhone application is landscape-only as per + * UISupportedInterfaceOrientations, the view controller's orientation is + * landscape. In this case the image must be rotated in order to appear + * correctly. + */ + BOOL isIPad = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad; + if (UIInterfaceOrientationIsLandscape(orientation) && !isIPad) { + imgTransform = CGAffineTransformMakeRotation(M_PI / 2); + imgBounds.size = CGSizeMake(imgBounds.size.height, imgBounds.size.width); + } + + // There's a special case when the image is the size of the screen. + if (CGSizeEqualToSize(screenSize, imgBounds.size)) { + CGRect statusFrame = [self.viewController.view convertRect:[UIApplication sharedApplication].statusBarFrame fromView:nil]; + if (!(IsAtLeastiOSVersion(@"7.0"))) { + imgBounds.origin.y -= statusFrame.size.height; + } + } else if (imgBounds.size.width > 0) { + CGRect viewBounds = self.viewController.view.bounds; + CGFloat imgAspect = imgBounds.size.width / imgBounds.size.height; + CGFloat viewAspect = viewBounds.size.width / viewBounds.size.height; + // This matches the behaviour of the native splash screen. + CGFloat ratio; + if (viewAspect > imgAspect) { + ratio = viewBounds.size.width / imgBounds.size.width; + } else { + ratio = viewBounds.size.height / imgBounds.size.height; + } + imgBounds.size.height *= ratio; + imgBounds.size.width *= ratio; + } + + _imageView.transform = imgTransform; + _imageView.frame = imgBounds; +} + +- (void)setVisible:(BOOL)visible +{ + if (visible == _visible) { + return; + } + _visible = visible; + + id fadeSplashScreenValue = [self.commandDelegate.settings objectForKey:[@"FadeSplashScreen" lowercaseString]]; + id fadeSplashScreenDuration = [self.commandDelegate.settings objectForKey:[@"FadeSplashScreenDuration" lowercaseString]]; + + float fadeDuration = fadeSplashScreenDuration == nil ? kSplashScreenDurationDefault : [fadeSplashScreenDuration floatValue]; + + if ((fadeSplashScreenValue == nil) || ![fadeSplashScreenValue boolValue]) { + fadeDuration = 0; + } + + // Never animate the showing of the splash screen. + if (visible) { + if (_imageView == nil) { + [self createViews]; + } + } else if (fadeDuration == 0) { + [self destroyViews]; + } else { + __weak __typeof(self) weakSelf = self; + + [UIView transitionWithView:self.viewController.view + duration:fadeDuration + options:UIViewAnimationOptionTransitionNone + animations:^(void) { + __typeof(self) strongSelf = weakSelf; + if (strongSelf != nil) { + dispatch_async(dispatch_get_main_queue(), ^{ + [strongSelf->_activityView setAlpha:0]; + [strongSelf->_imageView setAlpha:0]; + }); + } + } + completion:^(BOOL finished) { + if (finished) { + dispatch_async(dispatch_get_main_queue(), ^{ + [weakSelf destroyViews]; + }); + } + } + ]; + } +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVViewController+SplashScreen.h b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVViewController+SplashScreen.h new file mode 100644 index 00000000..a948ea31 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVViewController+SplashScreen.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 <Cordova/CDVViewController.h> + +@interface CDVViewController (SplashScreen) + +@property (nonatomic, assign) BOOL enabledAutorotation; +@property (nonatomic, readonly) BOOL shouldAutorotateDefaultValue; + + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVViewController+SplashScreen.m b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVViewController+SplashScreen.m new file mode 100644 index 00000000..5736b6f2 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Plugins/cordova-plugin-splashscreen/CDVViewController+SplashScreen.m @@ -0,0 +1,82 @@ +/* + 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 "CDVViewController+SplashScreen.h" +#import <objc/runtime.h> + +@implementation CDVViewController (SplashScreen) + +@dynamic enabledAutorotation; + +- (void)setEnabledAutorotation:(BOOL)value +{ + objc_setAssociatedObject(self, + @selector(enabledAutorotation), + [NSNumber numberWithBool:value], + OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)enabledAutorotation +{ + NSNumber *number = (NSNumber *)objc_getAssociatedObject(self, @selector(enabledAutorotation)); + return [number boolValue]; +} + ++ (void)load +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [self class]; + + SEL originalSelector = @selector(shouldAutorotate); + SEL swizzledSelector = @selector(splash_shouldAutorotate); + + Method originalMethod = class_getInstanceMethod(class, originalSelector); + Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); + + BOOL didAddMethod = class_addMethod(class, + originalSelector, + method_getImplementation(swizzledMethod), + method_getTypeEncoding(swizzledMethod)); + + if (didAddMethod) { + class_replaceMethod(class, + swizzledSelector, + method_getImplementation(originalMethod), + method_getTypeEncoding(originalMethod)); + } else { + method_exchangeImplementations(originalMethod, swizzledMethod); + } + }); +} + +#pragma mark - Method Swizzling + +- (BOOL)splash_shouldAutorotate +{ + return self.enabledAutorotation; +} + + +- (BOOL)shouldAutorotateDefaultValue +{ + return [self splash_shouldAutorotate]; +} + +@end diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/CDVNotification.bundle/beep.wav b/StoneIsland/platforms/ios/StoneIsland/Resources/CDVNotification.bundle/beep.wav Binary files differnew file mode 100644 index 00000000..05f5997f --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/CDVNotification.bundle/beep.wav diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-568h@2x~iphone.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-568h@2x~iphone.png Binary files differnew file mode 100644 index 00000000..10ed683c --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-568h@2x~iphone.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-667h.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-667h.png Binary files differnew file mode 100644 index 00000000..d9bcf61d --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-667h.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-736h.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-736h.png Binary files differnew file mode 100644 index 00000000..1fcef229 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-736h.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape-736h.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape-736h.png Binary files differnew file mode 100644 index 00000000..eae0792d --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape-736h.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape@2x~ipad.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape@2x~ipad.png Binary files differnew file mode 100644 index 00000000..1fc8c7db --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape@2x~ipad.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape~ipad.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape~ipad.png Binary files differnew file mode 100644 index 00000000..58ea2fbd --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Landscape~ipad.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Portrait@2x~ipad.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Portrait@2x~ipad.png Binary files differnew file mode 100644 index 00000000..1570b37d --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Portrait@2x~ipad.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Portrait~ipad.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Portrait~ipad.png Binary files differnew file mode 100644 index 00000000..223e75d0 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default-Portrait~ipad.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default@2x~iphone.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default@2x~iphone.png Binary files differnew file mode 100644 index 00000000..0098dc73 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default@2x~iphone.png diff --git a/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default~iphone.png b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default~iphone.png Binary files differnew file mode 100644 index 00000000..42b8fdea --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/Resources/splash/Default~iphone.png diff --git a/StoneIsland/platforms/ios/StoneIsland/StoneIsland-Info.plist b/StoneIsland/platforms/ios/StoneIsland/StoneIsland-Info.plist new file mode 100644 index 00000000..882f8e0d --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/StoneIsland-Info.plist @@ -0,0 +1,177 @@ +<?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>English</string> + <key>CFBundleDisplayName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundleExecutable</key> + <string>${EXECUTABLE_NAME}</string> + <key>CFBundleIconFile</key> + <string>icon.png</string> + <key>CFBundleIcons</key> + <dict> + <key>CFBundlePrimaryIcon</key> + <dict> + <key>CFBundleIconFiles</key> + <array> + <string>icon-40</string> + <string>icon-small</string> + <string>icon-60</string> + <string>icon.png</string> + <string>icon@2x</string> + <string>icon-72</string> + <string>icon-72@2x</string> + </array> + <key>UIPrerenderedIcon</key> + <false/> + </dict> + </dict> + <key>CFBundleIcons~ipad</key> + <dict> + <key>CFBundlePrimaryIcon</key> + <dict> + <key>CFBundleIconFiles</key> + <array> + <string>icon-small</string> + <string>icon-40</string> + <string>icon-50</string> + <string>icon-76</string> + <string>icon-60</string> + <string>icon</string> + <string>icon@2x</string> + <string>icon-72</string> + <string>icon-72@2x</string> + </array> + <key>UIPrerenderedIcon</key> + <false/> + </dict> + </dict> + <key>CFBundleIdentifier</key> + <string>io.cordova.hellocordova</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>0.0.1</string> + <key>CFBundleShortVersionString</key> + <string>0.0.1</string> + <key>LSRequiresIPhoneOS</key> + <true/> + <key>NSMainNibFile</key> + <string></string> + <key>NSMainNibFile~ipad</key> + <string></string> + <key>UILaunchImages</key> + <array> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default</string> + <key>UILaunchImageOrientation</key> + <string>Portrait</string> + <key>UILaunchImageSize</key> + <string>{320, 480}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default</string> + <key>UILaunchImageOrientation</key> + <string>Landscape</string> + <key>UILaunchImageSize</key> + <string>{320, 480}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-568h</string> + <key>UILaunchImageOrientation</key> + <string>Portrait</string> + <key>UILaunchImageSize</key> + <string>{320, 568}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-568h</string> + <key>UILaunchImageOrientation</key> + <string>Landscape</string> + <key>UILaunchImageSize</key> + <string>{320, 568}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-667h</string> + <key>UILaunchImageOrientation</key> + <string>Portrait</string> + <key>UILaunchImageSize</key> + <string>{375, 667}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-667h</string> + <key>UILaunchImageOrientation</key> + <string>Landscape</string> + <key>UILaunchImageSize</key> + <string>{375, 667}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-736h</string> + <key>UILaunchImageOrientation</key> + <string>Portrait</string> + <key>UILaunchImageSize</key> + <string>{414, 736}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-Landscape-736h</string> + <key>UILaunchImageOrientation</key> + <string>Landscape</string> + <key>UILaunchImageSize</key> + <string>{414, 736}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-Portrait</string> + <key>UILaunchImageOrientation</key> + <string>Portrait</string> + <key>UILaunchImageSize</key> + <string>{768, 1024}</string> + </dict> + <dict> + <key>UILaunchImageMinimumOSVersion</key> + <string>8.0</string> + <key>UILaunchImageName</key> + <string>Default-Landscape</string> + <key>UILaunchImageOrientation</key> + <string>Landscape</string> + <key>UILaunchImageSize</key> + <string>{768, 1024}</string> + </dict> + </array> + <key>NSLocationWhenInUseUsageDescription</key> + <string></string> + </dict> +</plist>
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/StoneIsland/StoneIsland-Prefix.pch b/StoneIsland/platforms/ios/StoneIsland/StoneIsland-Prefix.pch new file mode 100644 index 00000000..e135f6ba --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/StoneIsland-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 'HelloCordova' target in the 'HelloCordova' project +// + +#ifdef __OBJC__ + #import <Foundation/Foundation.h> + #import <UIKit/UIKit.h> +#endif diff --git a/StoneIsland/platforms/ios/StoneIsland/config.xml b/StoneIsland/platforms/ios/StoneIsland/config.xml new file mode 100755 index 00000000..c102dc1a --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/config.xml @@ -0,0 +1,57 @@ +<?xml version='1.0' encoding='utf-8'?> +<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> + <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="GapBetweenPages" value="0" /> + <preference name="PageLength" value="0" /> + <preference name="PaginationBreakingMode" value="page" /> + <preference name="PaginationMode" value="unpaginated" /> + <feature name="LocalStorage"> + <param name="ios-package" value="CDVLocalStorage" /> + </feature> + <feature name="Keyboard"> + <param name="ios-package" onload="true" value="IonicKeyboard" /> + </feature> + <feature name="Console"> + <param name="ios-package" value="CDVLogger" /> + </feature> + <feature name="Device"> + <param name="ios-package" value="CDVDevice" /> + </feature> + <feature name="Notification"> + <param name="ios-package" value="CDVNotification" /> + </feature> + <feature name="Geolocation"> + <param name="ios-package" value="CDVLocation" /> + </feature> + <feature name="NetworkStatus"> + <param name="ios-package" value="CDVConnection" /> + </feature> + <feature name="SplashScreen"> + <param name="ios-package" value="CDVSplashScreen" /> + <param name="onload" value="true" /> + </feature> + <allow-intent href="itms:*" /> + <allow-intent href="itms-apps:*" /> + <preference name="BackupWebStorage" value="local" /> + <name>StoneIsland</name> + <description> + Stone Island app + </description> + <author email="frontdesk@okfoc.us" href="http://okfoc.us/"> + OKFocus + </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:*" /> +</widget> diff --git a/StoneIsland/platforms/ios/StoneIsland/main.m b/StoneIsland/platforms/ios/StoneIsland/main.m new file mode 100644 index 00000000..41282ad0 --- /dev/null +++ b/StoneIsland/platforms/ios/StoneIsland/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 +// HelloCordova +// +// 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/StoneIsland/platforms/ios/cordova/apple_ios_version b/StoneIsland/platforms/ios/cordova/apple_ios_version new file mode 100755 index 00000000..d397bb6b --- /dev/null +++ b/StoneIsland/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/StoneIsland/platforms/ios/cordova/apple_osx_version b/StoneIsland/platforms/ios/cordova/apple_osx_version new file mode 100755 index 00000000..6e697add --- /dev/null +++ b/StoneIsland/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/StoneIsland/platforms/ios/cordova/apple_xcode_version b/StoneIsland/platforms/ios/cordova/apple_xcode_version new file mode 100755 index 00000000..112eba32 --- /dev/null +++ b/StoneIsland/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/StoneIsland/platforms/ios/cordova/build b/StoneIsland/platforms/ios/cordova/build new file mode 100755 index 00000000..5007627f --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/build @@ -0,0 +1,36 @@ +#!/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 build = require('./lib/build'), + args = process.argv; + +// Handle help flag +if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(args[2]) > -1) { + build.help(); +} else { + build.run(args).done(function() { + console.log('** BUILD SUCCEEDED **'); + }, function(err) { + var errorMessage = (err && err.stack) ? err.stack : err; + console.error(errorMessage); + process.exit(2); + }); +}
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/build-debug.xcconfig b/StoneIsland/platforms/ios/cordova/build-debug.xcconfig new file mode 100755 index 00000000..85748ea8 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/build-debug.xcconfig @@ -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. +// + +// +// XCode Build settings for "Debug" Build Configuration. +// + +#include "build.xcconfig"
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/build-release.xcconfig b/StoneIsland/platforms/ios/cordova/build-release.xcconfig new file mode 100755 index 00000000..6169afd4 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/build-release.xcconfig @@ -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. +// + +// +// XCode Build settings for "Release" Build Configuration. +// + +#include "build.xcconfig" + +CODE_SIGN_IDENTITY = iPhone Distribution +CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/build.xcconfig b/StoneIsland/platforms/ios/cordova/build.xcconfig new file mode 100755 index 00000000..0b89ad0f --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/build.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 shared by all Build Configurations. +// Settings are overridden by configuration-level .xcconfig file (build-release/build-debug). +// + + +// 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-7872) Solution for XCode 6.1 signing errors related to resource envelope format deprecation +CODE_SIGN_RESOURCE_RULES_PATH = $(SDKROOT)/ResourceRules.plist
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/check_reqs b/StoneIsland/platforms/ios/cordova/check_reqs new file mode 100755 index 00000000..ba68ceb4 --- /dev/null +++ b/StoneIsland/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) { + check_reqs.help(); +} else { + check_reqs.run().done(null, function (err) { + console.error('Failed to check requirements due to ' + err); + process.exit(2); + }); +}
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/clean b/StoneIsland/platforms/ios/cordova/clean new file mode 100755 index 00000000..ae61078d --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/clean @@ -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 clean = require('./lib/clean'); + +clean.run(process.argv).done(function () { + console.log('** CLEAN SUCCEEDED **'); +}, function(err) { + console.error(err); + process.exit(2); +});
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/clean.bat b/StoneIsland/platforms/ios/cordova/clean.bat new file mode 100755 index 00000000..25f17901 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/clean.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="%~dp0clean" +IF EXIST %script_path% ( + node %script_path% %* +) ELSE ( + ECHO. + ECHO ERROR: Could not find 'clean' script in 'cordova' folder, aborting...>&2 + EXIT /B 1 +)
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/defaults.xml b/StoneIsland/platforms/ios/cordova/defaults.xml new file mode 100755 index 00000000..c98d846b --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/defaults.xml @@ -0,0 +1,40 @@ +<?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="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> +</widget> diff --git a/StoneIsland/platforms/ios/cordova/lib/build.js b/StoneIsland/platforms/ios/cordova/lib/build.js new file mode 100755 index 00000000..153a4ec3 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/build.js @@ -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. + */ + +/*jshint node: true*/ + +var Q = require('q'), + nopt = require('nopt'), + path = require('path'), + shell = require('shelljs'), + spawn = require('./spawn'), + check_reqs = require('./check_reqs'); + +var projectPath = path.join(__dirname, '..', '..'); + +module.exports.run = function (argv) { + + var args = nopt({ + // "archs": String, // TODO: add support for building different archs + 'debug': Boolean, + 'release': Boolean, + 'device': Boolean, + 'emulator': Boolean, + }, {'-r': '--release'}, argv); + + if (args.debug && args.release) { + return Q.reject('Only one of "debug"/"release" options should be specified'); + } + + if (args.device && args.emulator) { + return Q.reject('Only one of "device"/"emulator" options should be specified'); + } + + return check_reqs.run().then(function () { + return findXCodeProjectIn(projectPath); + }).then(function (projectName) { + var configuration = args.release ? 'Release' : 'Debug'; + + console.log('Building project : ' + path.join(projectPath, projectName + '.xcodeproj')); + console.log('\tConfiguration : ' + configuration); + console.log('\tPlatform : ' + (args.device ? 'device' : 'emulator')); + + var xcodebuildArgs = getXcodeArgs(projectName, projectPath, configuration, args.device); + return spawn('xcodebuild', xcodebuildArgs, projectPath); + }); +}; + +/** + * 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) { + console.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) + * @return {Array} Array of arguments that could be passed directly to spawn method + */ +function getXcodeArgs(projectName, projectPath, configuration, isDevice) { + var xcodebuildArgs; + if (isDevice) { + xcodebuildArgs = [ + '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'), + '-project', projectName + '.xcodeproj', + 'ARCHS=armv7 armv7s arm64', + '-target', projectName, + '-configuration', configuration, + '-sdk', 'iphoneos', + 'build', + 'VALID_ARCHS=armv7 armv7s arm64', + 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'), + 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch') + ]; + } else { // emulator + xcodebuildArgs = [ + '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'), + '-project', projectName + '.xcodeproj', + 'ARCHS=i386', + '-target', projectName , + '-configuration', configuration, + '-sdk', 'iphonesimulator', + 'build', + 'VALID_ARCHS=i386', + 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'), + 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch') + ]; + } + return xcodebuildArgs; +} + +// help/usage function +module.exports.help = function help() { + console.log(''); + console.log('Usage: build [ --debug | --release ] [--archs=\"<list of architectures...>\"] [--device | --simulator]'); + 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.'); + // 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('examples:'); + console.log(' build '); + console.log(' build --debug'); + console.log(' build --release'); + // TODO: add support for building different archs + // console.log(" build --release --archs=\"armv7\""); + console.log(''); + process.exit(0); +}; diff --git a/StoneIsland/platforms/ios/cordova/lib/check_reqs.js b/StoneIsland/platforms/ios/cordova/lib/check_reqs.js new file mode 100755 index 00000000..6b4cce56 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/check_reqs.js @@ -0,0 +1,94 @@ +/* + 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. +*/ + +/* jshint node:true, bitwise:true, undef:true, trailing:true, quotmark:true, + indent:4, unused:vars, latedef:nofunc, + sub:true, laxcomma:true, laxbreak:true +*/ + +var Q = require('Q'), + os = require('os'), + shell = require('shelljs'), + versions = require('./versions'); + +var XCODEBUILD_MIN_VERSION = '4.6.0'; + +var IOS_SIM_MIN_VERSION = '3.0.0'; +var IOS_SIM_NOT_FOUND_MESSAGE = 'ios-sim was not found. Please download, build and install version ' + IOS_SIM_MIN_VERSION + + ' or greater from https://github.com/phonegap/ios-sim into your path.' + + ' Or \'npm install -g ios-sim\' using node.js: http://nodejs.org'; + +var IOS_DEPLOY_MIN_VERSION = '1.2.0'; +var IOS_DEPLOY_NOT_FOUND_MESSAGE = 'ios-deploy was not found. Please download, build and install version ' + IOS_DEPLOY_MIN_VERSION + + ' or greater from https://github.com/phonegap/ios-deploy into your path.' + + ' Or \'npm install -g ios-deploy\' using node.js: http://nodejs.org'; + +/** + * 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); +}; + +/** + * 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); +}; + +/** + * Checks if ios-sim util is available + * @return {Promise} Returns a promise either resolved with ios-sim version or rejected + */ +module.exports.check_ios_sim = function () { + return checkTool('ios-sim', IOS_SIM_MIN_VERSION, IOS_SIM_NOT_FOUND_MESSAGE); +}; + +module.exports.help = function () { + console.log('Usage: check_reqs or node check_reqs'); +}; + +/** + * Checks if specific tool is available. + * @param {String} tool Tool name to check. Known tools are 'xcodebuild', 'ios-sim' and 'ios-deploy' + * @param {Number} minVersion Min allowed tool version. + * @param {String} optMessage Message that will be used to reject promise. + * @return {Promise} Returns a promise either resolved with tool version or rejected + */ +function checkTool (tool, minVersion, optMessage) { + if (os.platform() !== 'darwin'){ + // Build iOS apps available for OSX platform only, so we reject on others platforms + return Q.reject('Cordova tooling for iOS requires Apple OS X'); + } + // Check whether tool command is available at all + var tool_command = shell.which(tool); + if (!tool_command) { + return Q.reject(optMessage || (tool + 'command is unavailable.')); + } + // check if tool version is greater than specified one + return versions.get_tool_version(tool).then(function (version) { + return versions.compareVersions(version, minVersion) >= 0 ? + Q.resolve(version) : + Q.reject('Cordova needs ' + tool + ' version ' + minVersion + + ' or greater, you have version ' + version + '.'); + }); +} diff --git a/StoneIsland/platforms/ios/cordova/lib/clean.js b/StoneIsland/platforms/ios/cordova/lib/clean.js new file mode 100755 index 00000000..6d955cf1 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/clean.js @@ -0,0 +1,46 @@ +/** + * 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. + */ + +/*jshint node: true*/ + +var Q = require('q'), + path = require('path'), + shell = require('shelljs'), + spawn = require('./spawn'), + check_reqs = require('./check_reqs'); + +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 check_reqs.run().then(function() { + return spawn('xcodebuild', ['-project', projectName, '-configuration', 'Debug', '-alltargets', 'clean'], projectPath); + }).then(function () { + return spawn('xcodebuild', ['-project', projectName, '-configuration', 'Release', '-alltargets', 'clean'], projectPath); + }).then(function () { + return shell.rm('-rf', path.join(projectPath, 'build')); + }); +}; diff --git a/StoneIsland/platforms/ios/cordova/lib/copy-www-build-step.sh b/StoneIsland/platforms/ios/cordova/lib/copy-www-build-step.sh new file mode 100755 index 00000000..7b934d5f --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/copy-www-build-step.sh @@ -0,0 +1,87 @@ +#!/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/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 "Path does not exist: $SRC_DIR" + exit 1 +fi + +# Use full path to find to avoid conflict with macports find (CB-6383). +if [[ -n $COPY_HIDDEN ]]; then + alias do_find='/usr/bin/find "$SRC_DIR"' +else + alias do_find='/usr/bin/find -L "$SRC_DIR" -name ".*" -prune -o' +fi + +time ( +# Code signing files must be removed or else there are +# resource signing errors. +rm -rf "$DST_DIR" \ + "$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME/_CodeSignature" \ + "$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME/PkgInfo" \ + "$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME/embedded.mobileprovision" + +# Directories +for p in $(do_find -type d -print); do + subpath="${p#$SRC_DIR}" + mkdir "$DST_DIR$subpath" || exit 1 +done + +# Symlinks +for p in $(do_find -type l -print); do + subpath="${p#$SRC_DIR}" + source=$(readlink $SRC_DIR$subpath) + sourcetype=$(stat -f "%HT%SY" $source) + if [ "$sourcetype" = "Directory" ]; then + mkdir "$DST_DIR$subpath" || exit 2 + else + rsync -a "$source" "$DST_DIR$subpath" || exit 3 + fi +done + +# Files +for p in $(do_find -type f -print); do + subpath="${p#$SRC_DIR}" + if ! ln "$SRC_DIR$subpath" "$DST_DIR$subpath" 2>/dev/null; then + rsync -a "$SRC_DIR$subpath" "$DST_DIR$subpath" || exit 4 + fi +done + +# Copy the config.xml file. +cp -f "${PROJECT_FILE_PATH%.xcodeproj}/config.xml" "$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME" + +) +IFS=$ORIG_IFS + diff --git a/StoneIsland/platforms/ios/cordova/lib/list-devices b/StoneIsland/platforms/ios/cordova/lib/list-devices new file mode 100755 index 00000000..a12abd74 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/list-devices @@ -0,0 +1,62 @@ +#!/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. +*/ + +/*jshint node: true*/ + +var Q = require('Q'), + 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, 'system_profiler SPUSBDataType | sed -n -e \'/iPad/,/Serial/p\' | grep "Serial Number:" | awk -F ": " \'{print $2 " iPad"}\''), + Q.nfcall(exec, 'system_profiler SPUSBDataType | sed -n -e \'/iPhone/,/Serial/p\' | grep "Serial Number:" | awk -F ": " \'{print $2 " iPhone"}\''), + Q.nfcall(exec, 'system_profiler SPUSBDataType | sed -n -e \'/iPod/,/Serial/p\' | grep "Serial Number:" | awk -F ": " \'{print $2 " iPod"}\'') + ]; + + // wrap al lexec calls into promises and wait until they're fullfilled + return Q.all(commands).then(function (promises) { + var accumulator = []; + promises.forEach(function (promise) { + if (promise.state === 'fulfilled') { + // Each command promise resolves with array [stout, stderr], and we need stdout only + // Append stdout lines to accumulator + accumulator.concat(promise.value[0].trim().split('\n')); + } + }); + 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/StoneIsland/platforms/ios/cordova/lib/list-emulator-images b/StoneIsland/platforms/ios/cordova/lib/list-emulator-images new file mode 100755 index 00000000..0c7f0c55 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/list-emulator-images @@ -0,0 +1,53 @@ +#!/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. +*/ + +/*jshint node: true*/ + +var Q = require('q'), + exec = require('child_process').exec, + check_reqs = require('./check_reqs'); + +/** + * Gets list of iOS devices available for simulation + * @return {Promise} Promise fulfilled with list of devices available for simulation + */ +function listEmulatorImages () { + return check_reqs.check_ios_sim().then(function () { + return Q.nfcall(exec, 'ios-sim showdevicetypes 2>&1 | ' + + 'sed "s/com.apple.CoreSimulator.SimDeviceType.//g" | ' + + 'awk -F\',\' \'{print $1}\''); + }).then(function (stdio) { + // Exec promise resolves with array [stout, stderr], and we need stdout only + return stdio[0].trim().split('\n'); + }); +} + +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/StoneIsland/platforms/ios/cordova/lib/list-started-emulators b/StoneIsland/platforms/ios/cordova/lib/list-started-emulators new file mode 100755 index 00000000..1269e47a --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/list-started-emulators @@ -0,0 +1,51 @@ +#!/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. +*/ + +/*jshint node: true*/ + +var Q = require('q'), + 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/StoneIsland/platforms/ios/cordova/lib/run.js b/StoneIsland/platforms/ios/cordova/lib/run.js new file mode 100755 index 00000000..151cad2a --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/run.js @@ -0,0 +1,177 @@ +/* + 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. +*/ + +/*jshint node: true*/ + +var Q = require('q'), + nopt = require('nopt'), + path = require('path'), + build = require('./build'), + spawn = require('./spawn'), + check_reqs = require('./check_reqs'); + +var cordovaPath = path.join(__dirname, '..'); +var projectPath = path.join(__dirname, '..', '..'); + +module.exports.run = function (argv) { + + // parse args here + // --debug and --release args not parsed here + // but still valid since they can be passed down to build command + var args = nopt({ + // "archs": String, // TODO: add support for building different archs + 'list': Boolean, + 'nobuild': Boolean, + 'device': Boolean, 'emulator': Boolean, 'target': String + }, {}, argv); + + // Validate args + if (args.device && args.emulator) { + return Q.reject('Only one of "device"/"emulator" options should be specified'); + } + + // validate target device for ios-sim + // Valid values for "--target" (case sensitive): + var validTargets = ['iPhone-4s', 'iPhone-5', 'iPhone-5s', 'iPhone-6-Plus', 'iPhone-6', + 'iPad-2', 'iPad-Retina', 'iPad-Air', 'Resizable-iPhone', 'Resizable-iPad']; + if (args.target && validTargets.indexOf(args.target) < 0 ) { + return Q.reject(args.target + ' is not a valid target for emulator'); + } + + // support for CB-8168 `cordova/run --list` + if (args.list) { + if (args.device) return listDevices(); + if (args.emulator) return listEmulators(); + // if no --device or --emulator flag is specified, list both devices and emulators + return listDevices().then(function () { + return listEmulators(); + }); + } + + // check for either ios-sim or ios-deploy is available + // depending on arguments provided + var checkTools = args.device ? check_reqs.check_ios_deploy() : check_reqs.check_ios_sim(); + + return checkTools.then(function () { + // if --nobuild isn't specified then build app first + if (!args.nobuild) { + return build.run(argv); + } + }).then(function () { + return build.findXCodeProjectIn(projectPath); + }).then(function (projectName) { + var appPath = path.join(projectPath, 'build', (args.device ? 'device' : 'emulator'), projectName + '.app'); + // select command to run and arguments depending whether + // we're running on device/emulator + if (args.device) { + return checkDeviceConnected().then(function () { + return deployToDevice(appPath); + }, function () { + // if device connection check failed use emulator then + return deployToSim(appPath, args.target); + }); + } else { + return deployToSim(appPath, args.target); + } + }); +}; + +/** + * Checks if any iOS device is connected + * @return {Promise} Fullfilled when any device is connected, rejected otherwise + */ +function checkDeviceConnected() { + return spawn('ios-deploy', ['-c']); +} + +/** + * 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) { + // Deploying to device... + return spawn('ios-deploy', ['-d', '-b', appPath]); +} + +/** + * 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) { + // Select target device for emulator. Default is 'iPhone-6' + if (!target) { + target = 'iPhone-6'; + console.log('No target specified for emulator. Deploying to ' + target + ' simulator'); + } + var logPath = path.join(cordovaPath, 'console.log'); + var simArgs = ['launch', appPath, + '--devicetypeid', 'com.apple.CoreSimulator.SimDeviceType.' + target, + // We need to redirect simulator output here to use cordova/log command + // TODO: Is there any other way to get emulator's output to use in log command? + '--stderr', logPath, '--stdout', logPath, + '--exit']; + return spawn('ios-sim', simArgs); +} + +function listDevices() { + return require('./list-devices').run() + .then(function (devices) { + console.log('Available iOS Devices:'); + devices.forEach(function (device) { + console.log('\t' + device); + }); + }); +} + +function listEmulators() { + return require('./list-emulator-images').run() + .then(function (emulators) { + console.log('Available iOS Virtual Devices:'); + emulators.forEach(function (emulator) { + console.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\"'); + console.log(' run --device --release'); + console.log(' run --emulator --debug'); + console.log(''); + process.exit(0); +};
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/lib/spawn.js b/StoneIsland/platforms/ios/cordova/lib/spawn.js new file mode 100755 index 00000000..1cb31615 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/spawn.js @@ -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. +*/ + +/*jshint node: true*/ + +var Q = require('q'), + 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 + */ +module.exports = function(cmd, args, opt_cwd) { + 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) { + console.error('error caught: ' + e); + d.reject(e); + } + return d.promise; +}; diff --git a/StoneIsland/platforms/ios/cordova/lib/start-emulator b/StoneIsland/platforms/ios/cordova/lib/start-emulator new file mode 100755 index 00000000..624335b1 --- /dev/null +++ b/StoneIsland/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 file diff --git a/StoneIsland/platforms/ios/cordova/lib/versions.js b/StoneIsland/platforms/ios/cordova/lib/versions.js new file mode 100755 index 00000000..e22e499a --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/lib/versions.js @@ -0,0 +1,178 @@ +#!/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'), + Q = require('q'); + +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]*/, + versions = [], + 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]*/, + versions = [], + regexOSX = /^OS X \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 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(); + default: return Q.reject(toolName + ' is not valid tool name. Valid names are: \'xcodebuild\', \'ios-sim\' and \'ios-deploy\''); + } +}; + +/** + * Compares two semver-notated version strings. Returns number + * that indicates equality of provided version strings. + * @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 = function (version1, version2) { + function parseVer (version) { + return version.split('.').map(function (value) { + // try to convert version segment to Number + var parsed = Number(value); + // Number constructor is strict enough and will return NaN + // if conversion fails. In this case we won't be able to compare versions properly + if (isNaN(parsed)) { + throw 'Version should contain only numbers and dots'; + } + return parsed; + }); + } + var parsedVer1 = parseVer(version1); + var parsedVer2 = parseVer(version2); + + // Compare corresponding segments of each version + for (var i = 0; i < Math.max(parsedVer1.length, parsedVer2.length); i++) { + // if segment is not specified, assume that it is 0 + // E.g. 3.1 is equal to 3.1.0 + var ret = (parsedVer1[i] || 0) - (parsedVer2[i] || 0); + // if segments are not equal, we're finished + if (ret !== 0) return ret; + } + return 0; +}; diff --git a/StoneIsland/platforms/ios/cordova/log b/StoneIsland/platforms/ios/cordova/log new file mode 100755 index 00000000..b235b09f --- /dev/null +++ b/StoneIsland/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/StoneIsland/platforms/ios/cordova/node_modules/nopt/LICENSE b/StoneIsland/platforms/ios/cordova/node_modules/nopt/LICENSE new file mode 100755 index 00000000..05a40109 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/nopt/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +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. diff --git a/StoneIsland/platforms/ios/cordova/node_modules/nopt/lib/nopt.js b/StoneIsland/platforms/ios/cordova/node_modules/nopt/lib/nopt.js new file mode 100755 index 00000000..5309a00f --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/nopt/lib/nopt.js @@ -0,0 +1,414 @@ +// info about each config option. + +var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG + ? function () { console.error.apply(console, arguments) } + : function () {} + +var url = require("url") + , path = require("path") + , Stream = require("stream").Stream + , abbrev = require("abbrev") + +module.exports = exports = nopt +exports.clean = clean + +exports.typeDefs = + { String : { type: String, validate: validateString } + , Boolean : { type: Boolean, validate: validateBoolean } + , url : { type: url, validate: validateUrl } + , Number : { type: Number, validate: validateNumber } + , path : { type: path, validate: validatePath } + , Stream : { type: Stream, validate: validateStream } + , Date : { type: Date, validate: validateDate } + } + +function nopt (types, shorthands, args, slice) { + args = args || process.argv + types = types || {} + shorthands = shorthands || {} + if (typeof slice !== "number") slice = 2 + + debug(types, shorthands, args, slice) + + args = args.slice(slice) + var data = {} + , key + , remain = [] + , cooked = args + , original = args.slice(0) + + parse(args, data, remain, types, shorthands) + // now data is full + clean(data, types, exports.typeDefs) + data.argv = {remain:remain,cooked:cooked,original:original} + Object.defineProperty(data.argv, 'toString', { value: function () { + return this.original.map(JSON.stringify).join(" ") + }, enumerable: false }) + return data +} + +function clean (data, types, typeDefs) { + typeDefs = typeDefs || exports.typeDefs + var remove = {} + , typeDefault = [false, true, null, String, Array] + + Object.keys(data).forEach(function (k) { + if (k === "argv") return + var val = data[k] + , isArray = Array.isArray(val) + , type = types[k] + if (!isArray) val = [val] + if (!type) type = typeDefault + if (type === Array) type = typeDefault.concat(Array) + if (!Array.isArray(type)) type = [type] + + debug("val=%j", val) + debug("types=", type) + val = val.map(function (val) { + // if it's an unknown value, then parse false/true/null/numbers/dates + if (typeof val === "string") { + debug("string %j", val) + val = val.trim() + if ((val === "null" && ~type.indexOf(null)) + || (val === "true" && + (~type.indexOf(true) || ~type.indexOf(Boolean))) + || (val === "false" && + (~type.indexOf(false) || ~type.indexOf(Boolean)))) { + val = JSON.parse(val) + debug("jsonable %j", val) + } else if (~type.indexOf(Number) && !isNaN(val)) { + debug("convert to number", val) + val = +val + } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { + debug("convert to date", val) + val = new Date(val) + } + } + + if (!types.hasOwnProperty(k)) { + return val + } + + // allow `--no-blah` to set 'blah' to null if null is allowed + if (val === false && ~type.indexOf(null) && + !(~type.indexOf(false) || ~type.indexOf(Boolean))) { + val = null + } + + var d = {} + d[k] = val + debug("prevalidated val", d, val, types[k]) + if (!validate(d, k, val, types[k], typeDefs)) { + if (exports.invalidHandler) { + exports.invalidHandler(k, val, types[k], data) + } else if (exports.invalidHandler !== false) { + debug("invalid: "+k+"="+val, types[k]) + } + return remove + } + debug("validated val", d, val, types[k]) + return d[k] + }).filter(function (val) { return val !== remove }) + + if (!val.length) delete data[k] + else if (isArray) { + debug(isArray, data[k], val) + data[k] = val + } else data[k] = val[0] + + debug("k=%s val=%j", k, val, data[k]) + }) +} + +function validateString (data, k, val) { + data[k] = String(val) +} + +function validatePath (data, k, val) { + if (val === true) return false + if (val === null) return true + + val = String(val) + var homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\// + if (val.match(homePattern) && process.env.HOME) { + val = path.resolve(process.env.HOME, val.substr(2)) + } + data[k] = path.resolve(String(val)) + return true +} + +function validateNumber (data, k, val) { + debug("validate Number %j %j %j", k, val, isNaN(val)) + if (isNaN(val)) return false + data[k] = +val +} + +function validateDate (data, k, val) { + debug("validate Date %j %j %j", k, val, Date.parse(val)) + var s = Date.parse(val) + if (isNaN(s)) return false + data[k] = new Date(val) +} + +function validateBoolean (data, k, val) { + if (val instanceof Boolean) val = val.valueOf() + else if (typeof val === "string") { + if (!isNaN(val)) val = !!(+val) + else if (val === "null" || val === "false") val = false + else val = true + } else val = !!val + data[k] = val +} + +function validateUrl (data, k, val) { + val = url.parse(String(val)) + if (!val.host) return false + data[k] = val.href +} + +function validateStream (data, k, val) { + if (!(val instanceof Stream)) return false + data[k] = val +} + +function validate (data, k, val, type, typeDefs) { + // arrays are lists of types. + if (Array.isArray(type)) { + for (var i = 0, l = type.length; i < l; i ++) { + if (type[i] === Array) continue + if (validate(data, k, val, type[i], typeDefs)) return true + } + delete data[k] + return false + } + + // an array of anything? + if (type === Array) return true + + // NaN is poisonous. Means that something is not allowed. + if (type !== type) { + debug("Poison NaN", k, val, type) + delete data[k] + return false + } + + // explicit list of values + if (val === type) { + debug("Explicitly allowed %j", val) + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + return true + } + + // now go through the list of typeDefs, validate against each one. + var ok = false + , types = Object.keys(typeDefs) + for (var i = 0, l = types.length; i < l; i ++) { + debug("test type %j %j %j", k, val, types[i]) + var t = typeDefs[types[i]] + if (t && type === t.type) { + var d = {} + ok = false !== t.validate(d, k, val) + val = d[k] + if (ok) { + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + break + } + } + } + debug("OK? %j (%j %j %j)", ok, k, val, types[i]) + + if (!ok) delete data[k] + return ok +} + +function parse (args, data, remain, types, shorthands) { + debug("parse", args, data, remain) + + var key = null + , abbrevs = abbrev(Object.keys(types)) + , shortAbbr = abbrev(Object.keys(shorthands)) + + for (var i = 0; i < args.length; i ++) { + var arg = args[i] + debug("arg", arg) + + if (arg.match(/^-{2,}$/)) { + // done with keys. + // the rest are args. + remain.push.apply(remain, args.slice(i + 1)) + args[i] = "--" + break + } + var hadEq = false + if (arg.charAt(0) === "-" && arg.length > 1) { + if (arg.indexOf("=") !== -1) { + hadEq = true + var v = arg.split("=") + arg = v.shift() + v = v.join("=") + args.splice.apply(args, [i, 1].concat([arg, v])) + } + + // see if it's a shorthand + // if so, splice and back up to re-parse it. + var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) + debug("arg=%j shRes=%j", arg, shRes) + if (shRes) { + debug(arg, shRes) + args.splice.apply(args, [i, 1].concat(shRes)) + if (arg !== shRes[0]) { + i -- + continue + } + } + arg = arg.replace(/^-+/, "") + var no = null + while (arg.toLowerCase().indexOf("no-") === 0) { + no = !no + arg = arg.substr(3) + } + + if (abbrevs[arg]) arg = abbrevs[arg] + + var isArray = types[arg] === Array || + Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1 + + // allow unknown things to be arrays if specified multiple times. + if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) { + if (!Array.isArray(data[arg])) + data[arg] = [data[arg]] + isArray = true + } + + var val + , la = args[i + 1] + + var isBool = typeof no === 'boolean' || + types[arg] === Boolean || + Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 || + (typeof types[arg] === 'undefined' && !hadEq) || + (la === "false" && + (types[arg] === null || + Array.isArray(types[arg]) && ~types[arg].indexOf(null))) + + if (isBool) { + // just set and move along + val = !no + // however, also support --bool true or --bool false + if (la === "true" || la === "false") { + val = JSON.parse(la) + la = null + if (no) val = !val + i ++ + } + + // also support "foo":[Boolean, "bar"] and "--foo bar" + if (Array.isArray(types[arg]) && la) { + if (~types[arg].indexOf(la)) { + // an explicit type + val = la + i ++ + } else if ( la === "null" && ~types[arg].indexOf(null) ) { + // null allowed + val = null + i ++ + } else if ( !la.match(/^-{2,}[^-]/) && + !isNaN(la) && + ~types[arg].indexOf(Number) ) { + // number + val = +la + i ++ + } else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) { + // string + val = la + i ++ + } + } + + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + continue + } + + if (types[arg] === String && la === undefined) + la = "" + + if (la && la.match(/^-{2,}$/)) { + la = undefined + i -- + } + + val = la === undefined ? true : la + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + i ++ + continue + } + remain.push(arg) + } +} + +function resolveShort (arg, shorthands, shortAbbr, abbrevs) { + // handle single-char shorthands glommed together, like + // npm ls -glp, but only if there is one dash, and only if + // all of the chars are single-char shorthands, and it's + // not a match to some other abbrev. + arg = arg.replace(/^-+/, '') + + // if it's an exact known option, then don't go any further + if (abbrevs[arg] === arg) + return null + + // if it's an exact known shortopt, same deal + if (shorthands[arg]) { + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] + } + + // first check to see if this arg is a set of single-char shorthands + var singles = shorthands.___singles + if (!singles) { + singles = Object.keys(shorthands).filter(function (s) { + return s.length === 1 + }).reduce(function (l,r) { + l[r] = true + return l + }, {}) + shorthands.___singles = singles + debug('shorthand singles', singles) + } + + var chrs = arg.split("").filter(function (c) { + return singles[c] + }) + + if (chrs.join("") === arg) return chrs.map(function (c) { + return shorthands[c] + }).reduce(function (l, r) { + return l.concat(r) + }, []) + + + // if it's an arg abbrev, and not a literal shorthand, then prefer the arg + if (abbrevs[arg] && !shorthands[arg]) + return null + + // if it's an abbr for a shorthand, then use that + if (shortAbbr[arg]) + arg = shortAbbr[arg] + + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] +} diff --git a/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/LICENSE b/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/LICENSE new file mode 100755 index 00000000..05a40109 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +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. diff --git a/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/abbrev.js b/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/abbrev.js new file mode 100755 index 00000000..69cfeac5 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/abbrev.js @@ -0,0 +1,62 @@ + +module.exports = exports = abbrev.abbrev = abbrev + +abbrev.monkeyPatch = monkeyPatch + +function monkeyPatch () { + Object.defineProperty(Array.prototype, 'abbrev', { + value: function () { return abbrev(this) }, + enumerable: false, configurable: true, writable: true + }) + + Object.defineProperty(Object.prototype, 'abbrev', { + value: function () { return abbrev(Object.keys(this)) }, + enumerable: false, configurable: true, writable: true + }) +} + +function abbrev (list) { + if (arguments.length !== 1 || !Array.isArray(list)) { + list = Array.prototype.slice.call(arguments, 0) + } + for (var i = 0, l = list.length, args = [] ; i < l ; i ++) { + args[i] = typeof list[i] === "string" ? list[i] : String(list[i]) + } + + // sort them lexicographically, so that they're next to their nearest kin + args = args.sort(lexSort) + + // walk through each, seeing how much it has in common with the next and previous + var abbrevs = {} + , prev = "" + for (var i = 0, l = args.length ; i < l ; i ++) { + var current = args[i] + , next = args[i + 1] || "" + , nextMatches = true + , prevMatches = true + if (current === next) continue + for (var j = 0, cl = current.length ; j < cl ; j ++) { + var curChar = current.charAt(j) + nextMatches = nextMatches && curChar === next.charAt(j) + prevMatches = prevMatches && curChar === prev.charAt(j) + if (!nextMatches && !prevMatches) { + j ++ + break + } + } + prev = current + if (j === cl) { + abbrevs[current] = current + continue + } + for (var a = current.substr(0, j) ; j <= cl ; j ++) { + abbrevs[a] = current + a += current.charAt(j) + } + } + return abbrevs +} + +function lexSort (a, b) { + return a === b ? 0 : a > b ? 1 : -1 +} diff --git a/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/package.json b/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/package.json new file mode 100755 index 00000000..91f1dd9c --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/nopt/node_modules/abbrev/package.json @@ -0,0 +1,31 @@ +{ + "name": "abbrev", + "version": "1.0.5", + "description": "Like ruby's abbrev module, but in js", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "main": "abbrev.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/isaacs/abbrev-js" + }, + "license": { + "type": "MIT", + "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" + }, + "readme": "# abbrev-js\n\nJust like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).\n\nUsage:\n\n var abbrev = require(\"abbrev\");\n abbrev(\"foo\", \"fool\", \"folding\", \"flop\");\n \n // returns:\n { fl: 'flop'\n , flo: 'flop'\n , flop: 'flop'\n , fol: 'folding'\n , fold: 'folding'\n , foldi: 'folding'\n , foldin: 'folding'\n , folding: 'folding'\n , foo: 'foo'\n , fool: 'fool'\n }\n\nThis is handy for command-line scripts, or other cases where you want to be able to accept shorthands.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/abbrev-js/issues" + }, + "homepage": "https://github.com/isaacs/abbrev-js", + "_id": "abbrev@1.0.5", + "_shasum": "5d8257bd9ebe435e698b2fa431afde4fe7b10b03", + "_from": "abbrev@1", + "_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.5.tgz" +} diff --git a/StoneIsland/platforms/ios/cordova/node_modules/nopt/package.json b/StoneIsland/platforms/ios/cordova/node_modules/nopt/package.json new file mode 100755 index 00000000..62d0fe84 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/nopt/package.json @@ -0,0 +1,41 @@ +{ + "name": "nopt", + "version": "3.0.1", + "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "main": "lib/nopt.js", + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/isaacs/nopt" + }, + "bin": { + "nopt": "./bin/nopt.js" + }, + "license": { + "type": "MIT", + "url": "https://github.com/isaacs/nopt/raw/master/LICENSE" + }, + "dependencies": { + "abbrev": "1" + }, + "devDependencies": { + "tap": "~0.4.8" + }, + "readme": "If you want to write an option parser, and have it be good, there are\ntwo ways to do it. The Right Way, and the Wrong Way.\n\nThe Wrong Way is to sit down and write an option parser. We've all done\nthat.\n\nThe Right Way is to write some complex configurable program with so many\noptions that you go half-insane just trying to manage them all, and put\nit off with duct-tape solutions until you see exactly to the core of the\nproblem, and finally snap and write an awesome option parser.\n\nIf you want to write an option parser, don't write an option parser.\nWrite a package manager, or a source control system, or a service\nrestarter, or an operating system. You probably won't end up with a\ngood one of those, but if you don't give up, and you are relentless and\ndiligent enough in your procrastination, you may just end up with a very\nnice option parser.\n\n## USAGE\n\n // my-program.js\n var nopt = require(\"nopt\")\n , Stream = require(\"stream\").Stream\n , path = require(\"path\")\n , knownOpts = { \"foo\" : [String, null]\n , \"bar\" : [Stream, Number]\n , \"baz\" : path\n , \"bloo\" : [ \"big\", \"medium\", \"small\" ]\n , \"flag\" : Boolean\n , \"pick\" : Boolean\n , \"many\" : [String, Array]\n }\n , shortHands = { \"foofoo\" : [\"--foo\", \"Mr. Foo\"]\n , \"b7\" : [\"--bar\", \"7\"]\n , \"m\" : [\"--bloo\", \"medium\"]\n , \"p\" : [\"--pick\"]\n , \"f\" : [\"--flag\"]\n }\n // everything is optional.\n // knownOpts and shorthands default to {}\n // arg list defaults to process.argv\n // slice defaults to 2\n , parsed = nopt(knownOpts, shortHands, process.argv, 2)\n console.log(parsed)\n\nThis would give you support for any of the following:\n\n```bash\n$ node my-program.js --foo \"blerp\" --no-flag\n{ \"foo\" : \"blerp\", \"flag\" : false }\n\n$ node my-program.js ---bar 7 --foo \"Mr. Hand\" --flag\n{ bar: 7, foo: \"Mr. Hand\", flag: true }\n\n$ node my-program.js --foo \"blerp\" -f -----p\n{ foo: \"blerp\", flag: true, pick: true }\n\n$ node my-program.js -fp --foofoo\n{ foo: \"Mr. Foo\", flag: true, pick: true }\n\n$ node my-program.js --foofoo -- -fp # -- stops the flag parsing.\n{ foo: \"Mr. Foo\", argv: { remain: [\"-fp\"] } }\n\n$ node my-program.js --blatzk -fp # unknown opts are ok.\n{ blatzk: true, flag: true, pick: true }\n\n$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value\n{ blatzk: 1000, flag: true, pick: true }\n\n$ node my-program.js --no-blatzk -fp # unless they start with \"no-\"\n{ blatzk: false, flag: true, pick: true }\n\n$ node my-program.js --baz b/a/z # known paths are resolved.\n{ baz: \"/Users/isaacs/b/a/z\" }\n\n# if Array is one of the types, then it can take many\n# values, and will always be an array. The other types provided\n# specify what types are allowed in the list.\n\n$ node my-program.js --many 1 --many null --many foo\n{ many: [\"1\", \"null\", \"foo\"] }\n\n$ node my-program.js --many foo\n{ many: [\"foo\"] }\n```\n\nRead the tests at the bottom of `lib/nopt.js` for more examples of\nwhat this puppy can do.\n\n## Types\n\nThe following types are supported, and defined on `nopt.typeDefs`\n\n* String: A normal string. No parsing is done.\n* path: A file system path. Gets resolved against cwd if not absolute.\n* url: A url. If it doesn't parse, it isn't accepted.\n* Number: Must be numeric.\n* Date: Must parse as a date. If it does, and `Date` is one of the options,\n then it will return a Date object, not a string.\n* Boolean: Must be either `true` or `false`. If an option is a boolean,\n then it does not need a value, and its presence will imply `true` as\n the value. To negate boolean flags, do `--no-whatever` or `--whatever\n false`\n* NaN: Means that the option is strictly not allowed. Any value will\n fail.\n* Stream: An object matching the \"Stream\" class in node. Valuable\n for use when validating programmatically. (npm uses this to let you\n supply any WriteStream on the `outfd` and `logfd` config options.)\n* Array: If `Array` is specified as one of the types, then the value\n will be parsed as a list of options. This means that multiple values\n can be specified, and that the value will always be an array.\n\nIf a type is an array of values not on this list, then those are\nconsidered valid values. For instance, in the example above, the\n`--bloo` option can only be one of `\"big\"`, `\"medium\"`, or `\"small\"`,\nand any other value will be rejected.\n\nWhen parsing unknown fields, `\"true\"`, `\"false\"`, and `\"null\"` will be\ninterpreted as their JavaScript equivalents.\n\nYou can also mix types and values, or multiple types, in a list. For\ninstance `{ blah: [Number, null] }` would allow a value to be set to\neither a Number or null. When types are ordered, this implies a\npreference, and the first type that can be used to properly interpret\nthe value will be used.\n\nTo define a new type, add it to `nopt.typeDefs`. Each item in that\nhash is an object with a `type` member and a `validate` method. The\n`type` member is an object that matches what goes in the type list. The\n`validate` method is a function that gets called with `validate(data,\nkey, val)`. Validate methods should assign `data[key]` to the valid\nvalue of `val` if it can be handled properly, or return boolean\n`false` if it cannot.\n\nYou can also call `nopt.clean(data, types, typeDefs)` to clean up a\nconfig object and remove its invalid properties.\n\n## Error Handling\n\nBy default, nopt outputs a warning to standard error when invalid\noptions are found. You can change this behavior by assigning a method\nto `nopt.invalidHandler`. This method will be called with\nthe offending `nopt.invalidHandler(key, val, types)`.\n\nIf no `nopt.invalidHandler` is assigned, then it will console.error\nits whining. If it is assigned to boolean `false` then the warning is\nsuppressed.\n\n## Abbreviations\n\nYes, they are supported. If you define options like this:\n\n```javascript\n{ \"foolhardyelephants\" : Boolean\n, \"pileofmonkeys\" : Boolean }\n```\n\nThen this will work:\n\n```bash\nnode program.js --foolhar --pil\nnode program.js --no-f --pileofmon\n# etc.\n```\n\n## Shorthands\n\nShorthands are a hash of shorter option names to a snippet of args that\nthey expand to.\n\nIf multiple one-character shorthands are all combined, and the\ncombination does not unambiguously match any other option or shorthand,\nthen they will be broken up into their constituent parts. For example:\n\n```json\n{ \"s\" : [\"--loglevel\", \"silent\"]\n, \"g\" : \"--global\"\n, \"f\" : \"--force\"\n, \"p\" : \"--parseable\"\n, \"l\" : \"--long\"\n}\n```\n\n```bash\nnpm ls -sgflp\n# just like doing this:\nnpm ls --loglevel silent --global --force --long --parseable\n```\n\n## The Rest of the args\n\nThe config object returned by nopt is given a special member called\n`argv`, which is an object with the following fields:\n\n* `remain`: The remaining args after all the parsing has occurred.\n* `original`: The args as they originally appeared.\n* `cooked`: The args after flags and shorthands are expanded.\n\n## Slicing\n\nNode programs are called with more or less the exact argv as it appears\nin C land, after the v8 and node-specific options have been plucked off.\nAs such, `argv[0]` is always `node` and `argv[1]` is always the\nJavaScript program being run.\n\nThat's usually not very useful to you. So they're sliced off by\ndefault. If you want them, then you can pass in `0` as the last\nargument, or any other number that you'd like to slice off the start of\nthe list.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/nopt/issues" + }, + "homepage": "https://github.com/isaacs/nopt", + "_id": "nopt@3.0.1", + "_shasum": "bce5c42446a3291f47622a370abbf158fbbacbfd", + "_from": "nopt@", + "_resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.1.tgz" +} diff --git a/StoneIsland/platforms/ios/cordova/node_modules/q/LICENSE b/StoneIsland/platforms/ios/cordova/node_modules/q/LICENSE new file mode 100755 index 00000000..8a706b59 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/q/LICENSE @@ -0,0 +1,18 @@ +Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved. +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. diff --git a/StoneIsland/platforms/ios/cordova/node_modules/q/package.json b/StoneIsland/platforms/ios/cordova/node_modules/q/package.json new file mode 100755 index 00000000..7b7f3c6c --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/q/package.json @@ -0,0 +1,112 @@ +{ + "name": "q", + "version": "1.0.1", + "description": "A library for promises (CommonJS/Promises/A,B,D)", + "homepage": "https://github.com/kriskowal/q", + "author": { + "name": "Kris Kowal", + "email": "kris@cixar.com", + "url": "https://github.com/kriskowal" + }, + "keywords": [ + "q", + "promise", + "promises", + "promises-a", + "promises-aplus", + "deferred", + "future", + "async", + "flow control", + "fluent", + "browser", + "node" + ], + "contributors": [ + { + "name": "Kris Kowal", + "email": "kris@cixar.com", + "url": "https://github.com/kriskowal" + }, + { + "name": "Irakli Gozalishvili", + "email": "rfobic@gmail.com", + "url": "http://jeditoolkit.com" + }, + { + "name": "Domenic Denicola", + "email": "domenic@domenicdenicola.com", + "url": "http://domenicdenicola.com" + } + ], + "bugs": { + "url": "http://github.com/kriskowal/q/issues" + }, + "license": { + "type": "MIT", + "url": "http://github.com/kriskowal/q/raw/master/LICENSE" + }, + "main": "q.js", + "repository": { + "type": "git", + "url": "git://github.com/kriskowal/q.git" + }, + "engines": { + "node": ">=0.6.0", + "teleport": ">=0.2.0" + }, + "dependencies": {}, + "devDependencies": { + "jshint": "~2.1.9", + "cover": "*", + "jasmine-node": "1.11.0", + "opener": "*", + "promises-aplus-tests": "1.x", + "grunt": "~0.4.1", + "grunt-cli": "~0.1.9", + "grunt-contrib-uglify": "~0.2.2", + "matcha": "~0.2.0" + }, + "scripts": { + "test": "jasmine-node spec && promises-aplus-tests spec/aplus-adapter", + "test-browser": "opener spec/q-spec.html", + "benchmark": "matcha", + "lint": "jshint q.js", + "cover": "cover run node_modules/jasmine-node/bin/jasmine-node spec && cover report html && opener cover_html/index.html", + "minify": "grunt", + "prepublish": "grunt" + }, + "overlay": { + "teleport": { + "dependencies": { + "system": ">=0.0.4" + } + } + }, + "directories": { + "test": "./spec" + }, + "_id": "q@1.0.1", + "dist": { + "shasum": "11872aeedee89268110b10a718448ffb10112a14", + "tarball": "http://registry.npmjs.org/q/-/q-1.0.1.tgz" + }, + "_from": "q@", + "_npmVersion": "1.4.4", + "_npmUser": { + "name": "kriskowal", + "email": "kris.kowal@cixar.com" + }, + "maintainers": [ + { + "name": "kriskowal", + "email": "kris.kowal@cixar.com" + }, + { + "name": "domenic", + "email": "domenic@domenicdenicola.com" + } + ], + "_shasum": "11872aeedee89268110b10a718448ffb10112a14", + "_resolved": "https://registry.npmjs.org/q/-/q-1.0.1.tgz" +} diff --git a/StoneIsland/platforms/ios/cordova/node_modules/q/q.js b/StoneIsland/platforms/ios/cordova/node_modules/q/q.js new file mode 100755 index 00000000..df36027e --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/q/q.js @@ -0,0 +1,1904 @@ +// vim:ts=4:sts=4:sw=4: +/*! + * + * Copyright 2009-2012 Kris Kowal under the terms of the MIT + * license found at http://github.com/kriskowal/q/raw/master/LICENSE + * + * With parts by Tyler Close + * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found + * at http://www.opensource.org/licenses/mit-license.html + * Forked at ref_send.js version: 2009-05-11 + * + * With parts by Mark Miller + * Copyright (C) 2011 Google Inc. + * + * Licensed 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 (definition) { + // Turn off strict mode for this function so we can assign to global.Q + /* jshint strict: false */ + + // This file will function properly as a <script> tag, or a module + // using CommonJS and NodeJS or RequireJS module formats. In + // Common/Node/RequireJS, the module exports the Q API and when + // executed as a simple <script>, it creates a Q global instead. + + // Montage Require + if (typeof bootstrap === "function") { + bootstrap("promise", definition); + + // CommonJS + } else if (typeof exports === "object") { + module.exports = definition(); + + // RequireJS + } else if (typeof define === "function" && define.amd) { + define(definition); + + // SES (Secure EcmaScript) + } else if (typeof ses !== "undefined") { + if (!ses.ok()) { + return; + } else { + ses.makeQ = definition; + } + + // <script> + } else { + Q = definition(); + } + +})(function () { +"use strict"; + +var hasStacks = false; +try { + throw new Error(); +} catch (e) { + hasStacks = !!e.stack; +} + +// All code after this point will be filtered from stack traces reported +// by Q. +var qStartingLine = captureLine(); +var qFileName; + +// shims + +// used for fallback in "allResolved" +var noop = function () {}; + +// Use the fastest possible means to execute a task in a future turn +// of the event loop. +var nextTick =(function () { + // linked list of tasks (single, with head node) + var head = {task: void 0, next: null}; + var tail = head; + var flushing = false; + var requestTick = void 0; + var isNodeJS = false; + + function flush() { + /* jshint loopfunc: true */ + + while (head.next) { + head = head.next; + var task = head.task; + head.task = void 0; + var domain = head.domain; + + if (domain) { + head.domain = void 0; + domain.enter(); + } + + try { + task(); + + } catch (e) { + if (isNodeJS) { + // In node, uncaught exceptions are considered fatal errors. + // Re-throw them synchronously to interrupt flushing! + + // Ensure continuation if the uncaught exception is suppressed + // listening "uncaughtException" events (as domains does). + // Continue in next event to avoid tick recursion. + if (domain) { + domain.exit(); + } + setTimeout(flush, 0); + if (domain) { + domain.enter(); + } + + throw e; + + } else { + // In browsers, uncaught exceptions are not fatal. + // Re-throw them asynchronously to avoid slow-downs. + setTimeout(function() { + throw e; + }, 0); + } + } + + if (domain) { + domain.exit(); + } + } + + flushing = false; + } + + nextTick = function (task) { + tail = tail.next = { + task: task, + domain: isNodeJS && process.domain, + next: null + }; + + if (!flushing) { + flushing = true; + requestTick(); + } + }; + + if (typeof process !== "undefined" && process.nextTick) { + // Node.js before 0.9. Note that some fake-Node environments, like the + // Mocha test runner, introduce a `process` global without a `nextTick`. + isNodeJS = true; + + requestTick = function () { + process.nextTick(flush); + }; + + } else if (typeof setImmediate === "function") { + // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate + if (typeof window !== "undefined") { + requestTick = setImmediate.bind(window, flush); + } else { + requestTick = function () { + setImmediate(flush); + }; + } + + } else if (typeof MessageChannel !== "undefined") { + // modern browsers + // http://www.nonblocking.io/2011/06/windownexttick.html + var channel = new MessageChannel(); + // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create + // working message ports the first time a page loads. + channel.port1.onmessage = function () { + requestTick = requestPortTick; + channel.port1.onmessage = flush; + flush(); + }; + var requestPortTick = function () { + // Opera requires us to provide a message payload, regardless of + // whether we use it. + channel.port2.postMessage(0); + }; + requestTick = function () { + setTimeout(flush, 0); + requestPortTick(); + }; + + } else { + // old browsers + requestTick = function () { + setTimeout(flush, 0); + }; + } + + return nextTick; +})(); + +// Attempt to make generics safe in the face of downstream +// modifications. +// There is no situation where this is necessary. +// If you need a security guarantee, these primordials need to be +// deeply frozen anyway, and if you don’t need a security guarantee, +// this is just plain paranoid. +// However, this **might** have the nice side-effect of reducing the size of +// the minified code by reducing x.call() to merely x() +// See Mark Miller’s explanation of what this does. +// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming +var call = Function.call; +function uncurryThis(f) { + return function () { + return call.apply(f, arguments); + }; +} +// This is equivalent, but slower: +// uncurryThis = Function_bind.bind(Function_bind.call); +// http://jsperf.com/uncurrythis + +var array_slice = uncurryThis(Array.prototype.slice); + +var array_reduce = uncurryThis( + Array.prototype.reduce || function (callback, basis) { + var index = 0, + length = this.length; + // concerning the initial value, if one is not provided + if (arguments.length === 1) { + // seek to the first value in the array, accounting + // for the possibility that is is a sparse array + do { + if (index in this) { + basis = this[index++]; + break; + } + if (++index >= length) { + throw new TypeError(); + } + } while (1); + } + // reduce + for (; index < length; index++) { + // account for the possibility that the array is sparse + if (index in this) { + basis = callback(basis, this[index], index); + } + } + return basis; + } +); + +var array_indexOf = uncurryThis( + Array.prototype.indexOf || function (value) { + // not a very good shim, but good enough for our one use of it + for (var i = 0; i < this.length; i++) { + if (this[i] === value) { + return i; + } + } + return -1; + } +); + +var array_map = uncurryThis( + Array.prototype.map || function (callback, thisp) { + var self = this; + var collect = []; + array_reduce(self, function (undefined, value, index) { + collect.push(callback.call(thisp, value, index, self)); + }, void 0); + return collect; + } +); + +var object_create = Object.create || function (prototype) { + function Type() { } + Type.prototype = prototype; + return new Type(); +}; + +var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); + +var object_keys = Object.keys || function (object) { + var keys = []; + for (var key in object) { + if (object_hasOwnProperty(object, key)) { + keys.push(key); + } + } + return keys; +}; + +var object_toString = uncurryThis(Object.prototype.toString); + +function isObject(value) { + return value === Object(value); +} + +// generator related shims + +// FIXME: Remove this function once ES6 generators are in SpiderMonkey. +function isStopIteration(exception) { + return ( + object_toString(exception) === "[object StopIteration]" || + exception instanceof QReturnValue + ); +} + +// FIXME: Remove this helper and Q.return once ES6 generators are in +// SpiderMonkey. +var QReturnValue; +if (typeof ReturnValue !== "undefined") { + QReturnValue = ReturnValue; +} else { + QReturnValue = function (value) { + this.value = value; + }; +} + +// long stack traces + +var STACK_JUMP_SEPARATOR = "From previous event:"; + +function makeStackTraceLong(error, promise) { + // If possible, transform the error stack trace by removing Node and Q + // cruft, then concatenating with the stack trace of `promise`. See #57. + if (hasStacks && + promise.stack && + typeof error === "object" && + error !== null && + error.stack && + error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 + ) { + var stacks = []; + for (var p = promise; !!p; p = p.source) { + if (p.stack) { + stacks.unshift(p.stack); + } + } + stacks.unshift(error.stack); + + var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); + error.stack = filterStackString(concatedStacks); + } +} + +function filterStackString(stackString) { + var lines = stackString.split("\n"); + var desiredLines = []; + for (var i = 0; i < lines.length; ++i) { + var line = lines[i]; + + if (!isInternalFrame(line) && !isNodeFrame(line) && line) { + desiredLines.push(line); + } + } + return desiredLines.join("\n"); +} + +function isNodeFrame(stackLine) { + return stackLine.indexOf("(module.js:") !== -1 || + stackLine.indexOf("(node.js:") !== -1; +} + +function getFileNameAndLineNumber(stackLine) { + // Named functions: "at functionName (filename:lineNumber:columnNumber)" + // In IE10 function name can have spaces ("Anonymous function") O_o + var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); + if (attempt1) { + return [attempt1[1], Number(attempt1[2])]; + } + + // Anonymous functions: "at filename:lineNumber:columnNumber" + var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); + if (attempt2) { + return [attempt2[1], Number(attempt2[2])]; + } + + // Firefox style: "function@filename:lineNumber or @filename:lineNumber" + var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); + if (attempt3) { + return [attempt3[1], Number(attempt3[2])]; + } +} + +function isInternalFrame(stackLine) { + var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); + + if (!fileNameAndLineNumber) { + return false; + } + + var fileName = fileNameAndLineNumber[0]; + var lineNumber = fileNameAndLineNumber[1]; + + return fileName === qFileName && + lineNumber >= qStartingLine && + lineNumber <= qEndingLine; +} + +// discover own file name and line number range for filtering stack +// traces +function captureLine() { + if (!hasStacks) { + return; + } + + try { + throw new Error(); + } catch (e) { + var lines = e.stack.split("\n"); + var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; + var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); + if (!fileNameAndLineNumber) { + return; + } + + qFileName = fileNameAndLineNumber[0]; + return fileNameAndLineNumber[1]; + } +} + +function deprecate(callback, name, alternative) { + return function () { + if (typeof console !== "undefined" && + typeof console.warn === "function") { + console.warn(name + " is deprecated, use " + alternative + + " instead.", new Error("").stack); + } + return callback.apply(callback, arguments); + }; +} + +// end of shims +// beginning of real work + +/** + * Constructs a promise for an immediate reference, passes promises through, or + * coerces promises from different systems. + * @param value immediate reference or promise + */ +function Q(value) { + // If the object is already a Promise, return it directly. This enables + // the resolve function to both be used to created references from objects, + // but to tolerably coerce non-promises to promises. + if (isPromise(value)) { + return value; + } + + // assimilate thenables + if (isPromiseAlike(value)) { + return coerce(value); + } else { + return fulfill(value); + } +} +Q.resolve = Q; + +/** + * Performs a task in a future turn of the event loop. + * @param {Function} task + */ +Q.nextTick = nextTick; + +/** + * Controls whether or not long stack traces will be on + */ +Q.longStackSupport = false; + +/** + * Constructs a {promise, resolve, reject} object. + * + * `resolve` is a callback to invoke with a more resolved value for the + * promise. To fulfill the promise, invoke `resolve` with any value that is + * not a thenable. To reject the promise, invoke `resolve` with a rejected + * thenable, or invoke `reject` with the reason directly. To resolve the + * promise to another thenable, thus putting it in the same state, invoke + * `resolve` with that other thenable. + */ +Q.defer = defer; +function defer() { + // if "messages" is an "Array", that indicates that the promise has not yet + // been resolved. If it is "undefined", it has been resolved. Each + // element of the messages array is itself an array of complete arguments to + // forward to the resolved promise. We coerce the resolution value to a + // promise using the `resolve` function because it handles both fully + // non-thenable values and other thenables gracefully. + var messages = [], progressListeners = [], resolvedPromise; + + var deferred = object_create(defer.prototype); + var promise = object_create(Promise.prototype); + + promise.promiseDispatch = function (resolve, op, operands) { + var args = array_slice(arguments); + if (messages) { + messages.push(args); + if (op === "when" && operands[1]) { // progress operand + progressListeners.push(operands[1]); + } + } else { + nextTick(function () { + resolvedPromise.promiseDispatch.apply(resolvedPromise, args); + }); + } + }; + + // XXX deprecated + promise.valueOf = function () { + if (messages) { + return promise; + } + var nearerValue = nearer(resolvedPromise); + if (isPromise(nearerValue)) { + resolvedPromise = nearerValue; // shorten chain + } + return nearerValue; + }; + + promise.inspect = function () { + if (!resolvedPromise) { + return { state: "pending" }; + } + return resolvedPromise.inspect(); + }; + + if (Q.longStackSupport && hasStacks) { + try { + throw new Error(); + } catch (e) { + // NOTE: don't try to use `Error.captureStackTrace` or transfer the + // accessor around; that causes memory leaks as per GH-111. Just + // reify the stack trace as a string ASAP. + // + // At the same time, cut off the first line; it's always just + // "[object Promise]\n", as per the `toString`. + promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1); + } + } + + // NOTE: we do the checks for `resolvedPromise` in each method, instead of + // consolidating them into `become`, since otherwise we'd create new + // promises with the lines `become(whatever(value))`. See e.g. GH-252. + + function become(newPromise) { + resolvedPromise = newPromise; + promise.source = newPromise; + + array_reduce(messages, function (undefined, message) { + nextTick(function () { + newPromise.promiseDispatch.apply(newPromise, message); + }); + }, void 0); + + messages = void 0; + progressListeners = void 0; + } + + deferred.promise = promise; + deferred.resolve = function (value) { + if (resolvedPromise) { + return; + } + + become(Q(value)); + }; + + deferred.fulfill = function (value) { + if (resolvedPromise) { + return; + } + + become(fulfill(value)); + }; + deferred.reject = function (reason) { + if (resolvedPromise) { + return; + } + + become(reject(reason)); + }; + deferred.notify = function (progress) { + if (resolvedPromise) { + return; + } + + array_reduce(progressListeners, function (undefined, progressListener) { + nextTick(function () { + progressListener(progress); + }); + }, void 0); + }; + + return deferred; +} + +/** + * Creates a Node-style callback that will resolve or reject the deferred + * promise. + * @returns a nodeback + */ +defer.prototype.makeNodeResolver = function () { + var self = this; + return function (error, value) { + if (error) { + self.reject(error); + } else if (arguments.length > 2) { + self.resolve(array_slice(arguments, 1)); + } else { + self.resolve(value); + } + }; +}; + +/** + * @param resolver {Function} a function that returns nothing and accepts + * the resolve, reject, and notify functions for a deferred. + * @returns a promise that may be resolved with the given resolve and reject + * functions, or rejected by a thrown exception in resolver + */ +Q.Promise = promise; // ES6 +Q.promise = promise; +function promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function."); + } + var deferred = defer(); + try { + resolver(deferred.resolve, deferred.reject, deferred.notify); + } catch (reason) { + deferred.reject(reason); + } + return deferred.promise; +} + +promise.race = race; // ES6 +promise.all = all; // ES6 +promise.reject = reject; // ES6 +promise.resolve = Q; // ES6 + +// XXX experimental. This method is a way to denote that a local value is +// serializable and should be immediately dispatched to a remote upon request, +// instead of passing a reference. +Q.passByCopy = function (object) { + //freeze(object); + //passByCopies.set(object, true); + return object; +}; + +Promise.prototype.passByCopy = function () { + //freeze(object); + //passByCopies.set(object, true); + return this; +}; + +/** + * If two promises eventually fulfill to the same value, promises that value, + * but otherwise rejects. + * @param x {Any*} + * @param y {Any*} + * @returns {Any*} a promise for x and y if they are the same, but a rejection + * otherwise. + * + */ +Q.join = function (x, y) { + return Q(x).join(y); +}; + +Promise.prototype.join = function (that) { + return Q([this, that]).spread(function (x, y) { + if (x === y) { + // TODO: "===" should be Object.is or equiv + return x; + } else { + throw new Error("Can't join: not the same: " + x + " " + y); + } + }); +}; + +/** + * Returns a promise for the first of an array of promises to become fulfilled. + * @param answers {Array[Any*]} promises to race + * @returns {Any*} the first promise to be fulfilled + */ +Q.race = race; +function race(answerPs) { + return promise(function(resolve, reject) { + // Switch to this once we can assume at least ES5 + // answerPs.forEach(function(answerP) { + // Q(answerP).then(resolve, reject); + // }); + // Use this in the meantime + for (var i = 0, len = answerPs.length; i < len; i++) { + Q(answerPs[i]).then(resolve, reject); + } + }); +} + +Promise.prototype.race = function () { + return this.then(Q.race); +}; + +/** + * Constructs a Promise with a promise descriptor object and optional fallback + * function. The descriptor contains methods like when(rejected), get(name), + * set(name, value), post(name, args), and delete(name), which all + * return either a value, a promise for a value, or a rejection. The fallback + * accepts the operation name, a resolver, and any further arguments that would + * have been forwarded to the appropriate method above had a method been + * provided with the proper name. The API makes no guarantees about the nature + * of the returned object, apart from that it is usable whereever promises are + * bought and sold. + */ +Q.makePromise = Promise; +function Promise(descriptor, fallback, inspect) { + if (fallback === void 0) { + fallback = function (op) { + return reject(new Error( + "Promise does not support operation: " + op + )); + }; + } + if (inspect === void 0) { + inspect = function () { + return {state: "unknown"}; + }; + } + + var promise = object_create(Promise.prototype); + + promise.promiseDispatch = function (resolve, op, args) { + var result; + try { + if (descriptor[op]) { + result = descriptor[op].apply(promise, args); + } else { + result = fallback.call(promise, op, args); + } + } catch (exception) { + result = reject(exception); + } + if (resolve) { + resolve(result); + } + }; + + promise.inspect = inspect; + + // XXX deprecated `valueOf` and `exception` support + if (inspect) { + var inspected = inspect(); + if (inspected.state === "rejected") { + promise.exception = inspected.reason; + } + + promise.valueOf = function () { + var inspected = inspect(); + if (inspected.state === "pending" || + inspected.state === "rejected") { + return promise; + } + return inspected.value; + }; + } + + return promise; +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.then = function (fulfilled, rejected, progressed) { + var self = this; + var deferred = defer(); + var done = false; // ensure the untrusted promise makes at most a + // single call to one of the callbacks + + function _fulfilled(value) { + try { + return typeof fulfilled === "function" ? fulfilled(value) : value; + } catch (exception) { + return reject(exception); + } + } + + function _rejected(exception) { + if (typeof rejected === "function") { + makeStackTraceLong(exception, self); + try { + return rejected(exception); + } catch (newException) { + return reject(newException); + } + } + return reject(exception); + } + + function _progressed(value) { + return typeof progressed === "function" ? progressed(value) : value; + } + + nextTick(function () { + self.promiseDispatch(function (value) { + if (done) { + return; + } + done = true; + + deferred.resolve(_fulfilled(value)); + }, "when", [function (exception) { + if (done) { + return; + } + done = true; + + deferred.resolve(_rejected(exception)); + }]); + }); + + // Progress propagator need to be attached in the current tick. + self.promiseDispatch(void 0, "when", [void 0, function (value) { + var newValue; + var threw = false; + try { + newValue = _progressed(value); + } catch (e) { + threw = true; + if (Q.onerror) { + Q.onerror(e); + } else { + throw e; + } + } + + if (!threw) { + deferred.notify(newValue); + } + }]); + + return deferred.promise; +}; + +/** + * Registers an observer on a promise. + * + * Guarantees: + * + * 1. that fulfilled and rejected will be called only once. + * 2. that either the fulfilled callback or the rejected callback will be + * called, but not both. + * 3. that fulfilled and rejected will not be called in this turn. + * + * @param value promise or immediate reference to observe + * @param fulfilled function to be called with the fulfilled value + * @param rejected function to be called with the rejection exception + * @param progressed function to be called on any progress notifications + * @return promise for the return value from the invoked callback + */ +Q.when = when; +function when(value, fulfilled, rejected, progressed) { + return Q(value).then(fulfilled, rejected, progressed); +} + +Promise.prototype.thenResolve = function (value) { + return this.then(function () { return value; }); +}; + +Q.thenResolve = function (promise, value) { + return Q(promise).thenResolve(value); +}; + +Promise.prototype.thenReject = function (reason) { + return this.then(function () { throw reason; }); +}; + +Q.thenReject = function (promise, reason) { + return Q(promise).thenReject(reason); +}; + +/** + * If an object is not a promise, it is as "near" as possible. + * If a promise is rejected, it is as "near" as possible too. + * If it’s a fulfilled promise, the fulfillment value is nearer. + * If it’s a deferred promise and the deferred has been resolved, the + * resolution is "nearer". + * @param object + * @returns most resolved (nearest) form of the object + */ + +// XXX should we re-do this? +Q.nearer = nearer; +function nearer(value) { + if (isPromise(value)) { + var inspected = value.inspect(); + if (inspected.state === "fulfilled") { + return inspected.value; + } + } + return value; +} + +/** + * @returns whether the given object is a promise. + * Otherwise it is a fulfilled value. + */ +Q.isPromise = isPromise; +function isPromise(object) { + return isObject(object) && + typeof object.promiseDispatch === "function" && + typeof object.inspect === "function"; +} + +Q.isPromiseAlike = isPromiseAlike; +function isPromiseAlike(object) { + return isObject(object) && typeof object.then === "function"; +} + +/** + * @returns whether the given object is a pending promise, meaning not + * fulfilled or rejected. + */ +Q.isPending = isPending; +function isPending(object) { + return isPromise(object) && object.inspect().state === "pending"; +} + +Promise.prototype.isPending = function () { + return this.inspect().state === "pending"; +}; + +/** + * @returns whether the given object is a value or fulfilled + * promise. + */ +Q.isFulfilled = isFulfilled; +function isFulfilled(object) { + return !isPromise(object) || object.inspect().state === "fulfilled"; +} + +Promise.prototype.isFulfilled = function () { + return this.inspect().state === "fulfilled"; +}; + +/** + * @returns whether the given object is a rejected promise. + */ +Q.isRejected = isRejected; +function isRejected(object) { + return isPromise(object) && object.inspect().state === "rejected"; +} + +Promise.prototype.isRejected = function () { + return this.inspect().state === "rejected"; +}; + +//// BEGIN UNHANDLED REJECTION TRACKING + +// This promise library consumes exceptions thrown in handlers so they can be +// handled by a subsequent promise. The exceptions get added to this array when +// they are created, and removed when they are handled. Note that in ES6 or +// shimmed environments, this would naturally be a `Set`. +var unhandledReasons = []; +var unhandledRejections = []; +var trackUnhandledRejections = true; + +function resetUnhandledRejections() { + unhandledReasons.length = 0; + unhandledRejections.length = 0; + + if (!trackUnhandledRejections) { + trackUnhandledRejections = true; + } +} + +function trackRejection(promise, reason) { + if (!trackUnhandledRejections) { + return; + } + + unhandledRejections.push(promise); + if (reason && typeof reason.stack !== "undefined") { + unhandledReasons.push(reason.stack); + } else { + unhandledReasons.push("(no stack) " + reason); + } +} + +function untrackRejection(promise) { + if (!trackUnhandledRejections) { + return; + } + + var at = array_indexOf(unhandledRejections, promise); + if (at !== -1) { + unhandledRejections.splice(at, 1); + unhandledReasons.splice(at, 1); + } +} + +Q.resetUnhandledRejections = resetUnhandledRejections; + +Q.getUnhandledReasons = function () { + // Make a copy so that consumers can't interfere with our internal state. + return unhandledReasons.slice(); +}; + +Q.stopUnhandledRejectionTracking = function () { + resetUnhandledRejections(); + trackUnhandledRejections = false; +}; + +resetUnhandledRejections(); + +//// END UNHANDLED REJECTION TRACKING + +/** + * Constructs a rejected promise. + * @param reason value describing the failure + */ +Q.reject = reject; +function reject(reason) { + var rejection = Promise({ + "when": function (rejected) { + // note that the error has been handled + if (rejected) { + untrackRejection(this); + } + return rejected ? rejected(reason) : this; + } + }, function fallback() { + return this; + }, function inspect() { + return { state: "rejected", reason: reason }; + }); + + // Note that the reason has not been handled. + trackRejection(rejection, reason); + + return rejection; +} + +/** + * Constructs a fulfilled promise for an immediate reference. + * @param value immediate reference + */ +Q.fulfill = fulfill; +function fulfill(value) { + return Promise({ + "when": function () { + return value; + }, + "get": function (name) { + return value[name]; + }, + "set": function (name, rhs) { + value[name] = rhs; + }, + "delete": function (name) { + delete value[name]; + }, + "post": function (name, args) { + // Mark Miller proposes that post with no name should apply a + // promised function. + if (name === null || name === void 0) { + return value.apply(void 0, args); + } else { + return value[name].apply(value, args); + } + }, + "apply": function (thisp, args) { + return value.apply(thisp, args); + }, + "keys": function () { + return object_keys(value); + } + }, void 0, function inspect() { + return { state: "fulfilled", value: value }; + }); +} + +/** + * Converts thenables to Q promises. + * @param promise thenable promise + * @returns a Q promise + */ +function coerce(promise) { + var deferred = defer(); + nextTick(function () { + try { + promise.then(deferred.resolve, deferred.reject, deferred.notify); + } catch (exception) { + deferred.reject(exception); + } + }); + return deferred.promise; +} + +/** + * Annotates an object such that it will never be + * transferred away from this process over any promise + * communication channel. + * @param object + * @returns promise a wrapping of that object that + * additionally responds to the "isDef" message + * without a rejection. + */ +Q.master = master; +function master(object) { + return Promise({ + "isDef": function () {} + }, function fallback(op, args) { + return dispatch(object, op, args); + }, function () { + return Q(object).inspect(); + }); +} + +/** + * Spreads the values of a promised array of arguments into the + * fulfillment callback. + * @param fulfilled callback that receives variadic arguments from the + * promised array + * @param rejected callback that receives the exception if the promise + * is rejected. + * @returns a promise for the return value or thrown exception of + * either callback. + */ +Q.spread = spread; +function spread(value, fulfilled, rejected) { + return Q(value).spread(fulfilled, rejected); +} + +Promise.prototype.spread = function (fulfilled, rejected) { + return this.all().then(function (array) { + return fulfilled.apply(void 0, array); + }, rejected); +}; + +/** + * The async function is a decorator for generator functions, turning + * them into asynchronous generators. Although generators are only part + * of the newest ECMAScript 6 drafts, this code does not cause syntax + * errors in older engines. This code should continue to work and will + * in fact improve over time as the language improves. + * + * ES6 generators are currently part of V8 version 3.19 with the + * --harmony-generators runtime flag enabled. SpiderMonkey has had them + * for longer, but under an older Python-inspired form. This function + * works on both kinds of generators. + * + * Decorates a generator function such that: + * - it may yield promises + * - execution will continue when that promise is fulfilled + * - the value of the yield expression will be the fulfilled value + * - it returns a promise for the return value (when the generator + * stops iterating) + * - the decorated function returns a promise for the return value + * of the generator or the first rejected promise among those + * yielded. + * - if an error is thrown in the generator, it propagates through + * every following yield until it is caught, or until it escapes + * the generator function altogether, and is translated into a + * rejection for the promise returned by the decorated generator. + */ +Q.async = async; +function async(makeGenerator) { + return function () { + // when verb is "send", arg is a value + // when verb is "throw", arg is an exception + function continuer(verb, arg) { + var result; + + // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only + // engine that has a deployed base of browsers that support generators. + // However, SM's generators use the Python-inspired semantics of + // outdated ES6 drafts. We would like to support ES6, but we'd also + // like to make it possible to use generators in deployed browsers, so + // we also support Python-style generators. At some point we can remove + // this block. + + if (typeof StopIteration === "undefined") { + // ES6 Generators + try { + result = generator[verb](arg); + } catch (exception) { + return reject(exception); + } + if (result.done) { + return result.value; + } else { + return when(result.value, callback, errback); + } + } else { + // SpiderMonkey Generators + // FIXME: Remove this case when SM does ES6 generators. + try { + result = generator[verb](arg); + } catch (exception) { + if (isStopIteration(exception)) { + return exception.value; + } else { + return reject(exception); + } + } + return when(result, callback, errback); + } + } + var generator = makeGenerator.apply(this, arguments); + var callback = continuer.bind(continuer, "next"); + var errback = continuer.bind(continuer, "throw"); + return callback(); + }; +} + +/** + * The spawn function is a small wrapper around async that immediately + * calls the generator and also ends the promise chain, so that any + * unhandled errors are thrown instead of forwarded to the error + * handler. This is useful because it's extremely common to run + * generators at the top-level to work with libraries. + */ +Q.spawn = spawn; +function spawn(makeGenerator) { + Q.done(Q.async(makeGenerator)()); +} + +// FIXME: Remove this interface once ES6 generators are in SpiderMonkey. +/** + * Throws a ReturnValue exception to stop an asynchronous generator. + * + * This interface is a stop-gap measure to support generator return + * values in older Firefox/SpiderMonkey. In browsers that support ES6 + * generators like Chromium 29, just use "return" in your generator + * functions. + * + * @param value the return value for the surrounding generator + * @throws ReturnValue exception with the value. + * @example + * // ES6 style + * Q.async(function* () { + * var foo = yield getFooPromise(); + * var bar = yield getBarPromise(); + * return foo + bar; + * }) + * // Older SpiderMonkey style + * Q.async(function () { + * var foo = yield getFooPromise(); + * var bar = yield getBarPromise(); + * Q.return(foo + bar); + * }) + */ +Q["return"] = _return; +function _return(value) { + throw new QReturnValue(value); +} + +/** + * The promised function decorator ensures that any promise arguments + * are settled and passed as values (`this` is also settled and passed + * as a value). It will also ensure that the result of a function is + * always a promise. + * + * @example + * var add = Q.promised(function (a, b) { + * return a + b; + * }); + * add(Q(a), Q(B)); + * + * @param {function} callback The function to decorate + * @returns {function} a function that has been decorated. + */ +Q.promised = promised; +function promised(callback) { + return function () { + return spread([this, all(arguments)], function (self, args) { + return callback.apply(self, args); + }); + }; +} + +/** + * sends a message to a value in a future turn + * @param object* the recipient + * @param op the name of the message operation, e.g., "when", + * @param args further arguments to be forwarded to the operation + * @returns result {Promise} a promise for the result of the operation + */ +Q.dispatch = dispatch; +function dispatch(object, op, args) { + return Q(object).dispatch(op, args); +} + +Promise.prototype.dispatch = function (op, args) { + var self = this; + var deferred = defer(); + nextTick(function () { + self.promiseDispatch(deferred.resolve, op, args); + }); + return deferred.promise; +}; + +/** + * Gets the value of a property in a future turn. + * @param object promise or immediate reference for target object + * @param name name of property to get + * @return promise for the property value + */ +Q.get = function (object, key) { + return Q(object).dispatch("get", [key]); +}; + +Promise.prototype.get = function (key) { + return this.dispatch("get", [key]); +}; + +/** + * Sets the value of a property in a future turn. + * @param object promise or immediate reference for object object + * @param name name of property to set + * @param value new value of property + * @return promise for the return value + */ +Q.set = function (object, key, value) { + return Q(object).dispatch("set", [key, value]); +}; + +Promise.prototype.set = function (key, value) { + return this.dispatch("set", [key, value]); +}; + +/** + * Deletes a property in a future turn. + * @param object promise or immediate reference for target object + * @param name name of property to delete + * @return promise for the return value + */ +Q.del = // XXX legacy +Q["delete"] = function (object, key) { + return Q(object).dispatch("delete", [key]); +}; + +Promise.prototype.del = // XXX legacy +Promise.prototype["delete"] = function (key) { + return this.dispatch("delete", [key]); +}; + +/** + * Invokes a method in a future turn. + * @param object promise or immediate reference for target object + * @param name name of method to invoke + * @param value a value to post, typically an array of + * invocation arguments for promises that + * are ultimately backed with `resolve` values, + * as opposed to those backed with URLs + * wherein the posted value can be any + * JSON serializable object. + * @return promise for the return value + */ +// bound locally because it is used by other methods +Q.mapply = // XXX As proposed by "Redsandro" +Q.post = function (object, name, args) { + return Q(object).dispatch("post", [name, args]); +}; + +Promise.prototype.mapply = // XXX As proposed by "Redsandro" +Promise.prototype.post = function (name, args) { + return this.dispatch("post", [name, args]); +}; + +/** + * Invokes a method in a future turn. + * @param object promise or immediate reference for target object + * @param name name of method to invoke + * @param ...args array of invocation arguments + * @return promise for the return value + */ +Q.send = // XXX Mark Miller's proposed parlance +Q.mcall = // XXX As proposed by "Redsandro" +Q.invoke = function (object, name /*...args*/) { + return Q(object).dispatch("post", [name, array_slice(arguments, 2)]); +}; + +Promise.prototype.send = // XXX Mark Miller's proposed parlance +Promise.prototype.mcall = // XXX As proposed by "Redsandro" +Promise.prototype.invoke = function (name /*...args*/) { + return this.dispatch("post", [name, array_slice(arguments, 1)]); +}; + +/** + * Applies the promised function in a future turn. + * @param object promise or immediate reference for target function + * @param args array of application arguments + */ +Q.fapply = function (object, args) { + return Q(object).dispatch("apply", [void 0, args]); +}; + +Promise.prototype.fapply = function (args) { + return this.dispatch("apply", [void 0, args]); +}; + +/** + * Calls the promised function in a future turn. + * @param object promise or immediate reference for target function + * @param ...args array of application arguments + */ +Q["try"] = +Q.fcall = function (object /* ...args*/) { + return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]); +}; + +Promise.prototype.fcall = function (/*...args*/) { + return this.dispatch("apply", [void 0, array_slice(arguments)]); +}; + +/** + * Binds the promised function, transforming return values into a fulfilled + * promise and thrown errors into a rejected one. + * @param object promise or immediate reference for target function + * @param ...args array of application arguments + */ +Q.fbind = function (object /*...args*/) { + var promise = Q(object); + var args = array_slice(arguments, 1); + return function fbound() { + return promise.dispatch("apply", [ + this, + args.concat(array_slice(arguments)) + ]); + }; +}; +Promise.prototype.fbind = function (/*...args*/) { + var promise = this; + var args = array_slice(arguments); + return function fbound() { + return promise.dispatch("apply", [ + this, + args.concat(array_slice(arguments)) + ]); + }; +}; + +/** + * Requests the names of the owned properties of a promised + * object in a future turn. + * @param object promise or immediate reference for target object + * @return promise for the keys of the eventually settled object + */ +Q.keys = function (object) { + return Q(object).dispatch("keys", []); +}; + +Promise.prototype.keys = function () { + return this.dispatch("keys", []); +}; + +/** + * Turns an array of promises into a promise for an array. If any of + * the promises gets rejected, the whole array is rejected immediately. + * @param {Array*} an array (or promise for an array) of values (or + * promises for values) + * @returns a promise for an array of the corresponding values + */ +// By Mark Miller +// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled +Q.all = all; +function all(promises) { + return when(promises, function (promises) { + var countDown = 0; + var deferred = defer(); + array_reduce(promises, function (undefined, promise, index) { + var snapshot; + if ( + isPromise(promise) && + (snapshot = promise.inspect()).state === "fulfilled" + ) { + promises[index] = snapshot.value; + } else { + ++countDown; + when( + promise, + function (value) { + promises[index] = value; + if (--countDown === 0) { + deferred.resolve(promises); + } + }, + deferred.reject, + function (progress) { + deferred.notify({ index: index, value: progress }); + } + ); + } + }, void 0); + if (countDown === 0) { + deferred.resolve(promises); + } + return deferred.promise; + }); +} + +Promise.prototype.all = function () { + return all(this); +}; + +/** + * Waits for all promises to be settled, either fulfilled or + * rejected. This is distinct from `all` since that would stop + * waiting at the first rejection. The promise returned by + * `allResolved` will never be rejected. + * @param promises a promise for an array (or an array) of promises + * (or values) + * @return a promise for an array of promises + */ +Q.allResolved = deprecate(allResolved, "allResolved", "allSettled"); +function allResolved(promises) { + return when(promises, function (promises) { + promises = array_map(promises, Q); + return when(all(array_map(promises, function (promise) { + return when(promise, noop, noop); + })), function () { + return promises; + }); + }); +} + +Promise.prototype.allResolved = function () { + return allResolved(this); +}; + +/** + * @see Promise#allSettled + */ +Q.allSettled = allSettled; +function allSettled(promises) { + return Q(promises).allSettled(); +} + +/** + * Turns an array of promises into a promise for an array of their states (as + * returned by `inspect`) when they have all settled. + * @param {Array[Any*]} values an array (or promise for an array) of values (or + * promises for values) + * @returns {Array[State]} an array of states for the respective values. + */ +Promise.prototype.allSettled = function () { + return this.then(function (promises) { + return all(array_map(promises, function (promise) { + promise = Q(promise); + function regardless() { + return promise.inspect(); + } + return promise.then(regardless, regardless); + })); + }); +}; + +/** + * Captures the failure of a promise, giving an oportunity to recover + * with a callback. If the given promise is fulfilled, the returned + * promise is fulfilled. + * @param {Any*} promise for something + * @param {Function} callback to fulfill the returned promise if the + * given promise is rejected + * @returns a promise for the return value of the callback + */ +Q.fail = // XXX legacy +Q["catch"] = function (object, rejected) { + return Q(object).then(void 0, rejected); +}; + +Promise.prototype.fail = // XXX legacy +Promise.prototype["catch"] = function (rejected) { + return this.then(void 0, rejected); +}; + +/** + * Attaches a listener that can respond to progress notifications from a + * promise's originating deferred. This listener receives the exact arguments + * passed to ``deferred.notify``. + * @param {Any*} promise for something + * @param {Function} callback to receive any progress notifications + * @returns the given promise, unchanged + */ +Q.progress = progress; +function progress(object, progressed) { + return Q(object).then(void 0, void 0, progressed); +} + +Promise.prototype.progress = function (progressed) { + return this.then(void 0, void 0, progressed); +}; + +/** + * Provides an opportunity to observe the settling of a promise, + * regardless of whether the promise is fulfilled or rejected. Forwards + * the resolution to the returned promise when the callback is done. + * The callback can return a promise to defer completion. + * @param {Any*} promise + * @param {Function} callback to observe the resolution of the given + * promise, takes no arguments. + * @returns a promise for the resolution of the given promise when + * ``fin`` is done. + */ +Q.fin = // XXX legacy +Q["finally"] = function (object, callback) { + return Q(object)["finally"](callback); +}; + +Promise.prototype.fin = // XXX legacy +Promise.prototype["finally"] = function (callback) { + callback = Q(callback); + return this.then(function (value) { + return callback.fcall().then(function () { + return value; + }); + }, function (reason) { + // TODO attempt to recycle the rejection with "this". + return callback.fcall().then(function () { + throw reason; + }); + }); +}; + +/** + * Terminates a chain of promises, forcing rejections to be + * thrown as exceptions. + * @param {Any*} promise at the end of a chain of promises + * @returns nothing + */ +Q.done = function (object, fulfilled, rejected, progress) { + return Q(object).done(fulfilled, rejected, progress); +}; + +Promise.prototype.done = function (fulfilled, rejected, progress) { + var onUnhandledError = function (error) { + // forward to a future turn so that ``when`` + // does not catch it and turn it into a rejection. + nextTick(function () { + makeStackTraceLong(error, promise); + if (Q.onerror) { + Q.onerror(error); + } else { + throw error; + } + }); + }; + + // Avoid unnecessary `nextTick`ing via an unnecessary `when`. + var promise = fulfilled || rejected || progress ? + this.then(fulfilled, rejected, progress) : + this; + + if (typeof process === "object" && process && process.domain) { + onUnhandledError = process.domain.bind(onUnhandledError); + } + + promise.then(void 0, onUnhandledError); +}; + +/** + * Causes a promise to be rejected if it does not get fulfilled before + * some milliseconds time out. + * @param {Any*} promise + * @param {Number} milliseconds timeout + * @param {String} custom error message (optional) + * @returns a promise for the resolution of the given promise if it is + * fulfilled before the timeout, otherwise rejected. + */ +Q.timeout = function (object, ms, message) { + return Q(object).timeout(ms, message); +}; + +Promise.prototype.timeout = function (ms, message) { + var deferred = defer(); + var timeoutId = setTimeout(function () { + deferred.reject(new Error(message || "Timed out after " + ms + " ms")); + }, ms); + + this.then(function (value) { + clearTimeout(timeoutId); + deferred.resolve(value); + }, function (exception) { + clearTimeout(timeoutId); + deferred.reject(exception); + }, deferred.notify); + + return deferred.promise; +}; + +/** + * Returns a promise for the given value (or promised value), some + * milliseconds after it resolved. Passes rejections immediately. + * @param {Any*} promise + * @param {Number} milliseconds + * @returns a promise for the resolution of the given promise after milliseconds + * time has elapsed since the resolution of the given promise. + * If the given promise rejects, that is passed immediately. + */ +Q.delay = function (object, timeout) { + if (timeout === void 0) { + timeout = object; + object = void 0; + } + return Q(object).delay(timeout); +}; + +Promise.prototype.delay = function (timeout) { + return this.then(function (value) { + var deferred = defer(); + setTimeout(function () { + deferred.resolve(value); + }, timeout); + return deferred.promise; + }); +}; + +/** + * Passes a continuation to a Node function, which is called with the given + * arguments provided as an array, and returns a promise. + * + * Q.nfapply(FS.readFile, [__filename]) + * .then(function (content) { + * }) + * + */ +Q.nfapply = function (callback, args) { + return Q(callback).nfapply(args); +}; + +Promise.prototype.nfapply = function (args) { + var deferred = defer(); + var nodeArgs = array_slice(args); + nodeArgs.push(deferred.makeNodeResolver()); + this.fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; +}; + +/** + * Passes a continuation to a Node function, which is called with the given + * arguments provided individually, and returns a promise. + * @example + * Q.nfcall(FS.readFile, __filename) + * .then(function (content) { + * }) + * + */ +Q.nfcall = function (callback /*...args*/) { + var args = array_slice(arguments, 1); + return Q(callback).nfapply(args); +}; + +Promise.prototype.nfcall = function (/*...args*/) { + var nodeArgs = array_slice(arguments); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + this.fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; +}; + +/** + * Wraps a NodeJS continuation passing function and returns an equivalent + * version that returns a promise. + * @example + * Q.nfbind(FS.readFile, __filename)("utf-8") + * .then(console.log) + * .done() + */ +Q.nfbind = +Q.denodeify = function (callback /*...args*/) { + var baseArgs = array_slice(arguments, 1); + return function () { + var nodeArgs = baseArgs.concat(array_slice(arguments)); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + Q(callback).fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; + }; +}; + +Promise.prototype.nfbind = +Promise.prototype.denodeify = function (/*...args*/) { + var args = array_slice(arguments); + args.unshift(this); + return Q.denodeify.apply(void 0, args); +}; + +Q.nbind = function (callback, thisp /*...args*/) { + var baseArgs = array_slice(arguments, 2); + return function () { + var nodeArgs = baseArgs.concat(array_slice(arguments)); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + function bound() { + return callback.apply(thisp, arguments); + } + Q(bound).fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; + }; +}; + +Promise.prototype.nbind = function (/*thisp, ...args*/) { + var args = array_slice(arguments, 0); + args.unshift(this); + return Q.nbind.apply(void 0, args); +}; + +/** + * Calls a method of a Node-style object that accepts a Node-style + * callback with a given array of arguments, plus a provided callback. + * @param object an object that has the named method + * @param {String} name name of the method of object + * @param {Array} args arguments to pass to the method; the callback + * will be provided by Q and appended to these arguments. + * @returns a promise for the value or error + */ +Q.nmapply = // XXX As proposed by "Redsandro" +Q.npost = function (object, name, args) { + return Q(object).npost(name, args); +}; + +Promise.prototype.nmapply = // XXX As proposed by "Redsandro" +Promise.prototype.npost = function (name, args) { + var nodeArgs = array_slice(args || []); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); + return deferred.promise; +}; + +/** + * Calls a method of a Node-style object that accepts a Node-style + * callback, forwarding the given variadic arguments, plus a provided + * callback argument. + * @param object an object that has the named method + * @param {String} name name of the method of object + * @param ...args arguments to pass to the method; the callback will + * be provided by Q and appended to these arguments. + * @returns a promise for the value or error + */ +Q.nsend = // XXX Based on Mark Miller's proposed "send" +Q.nmcall = // XXX Based on "Redsandro's" proposal +Q.ninvoke = function (object, name /*...args*/) { + var nodeArgs = array_slice(arguments, 2); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject); + return deferred.promise; +}; + +Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send" +Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal +Promise.prototype.ninvoke = function (name /*...args*/) { + var nodeArgs = array_slice(arguments, 1); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); + return deferred.promise; +}; + +/** + * If a function would like to support both Node continuation-passing-style and + * promise-returning-style, it can end its internal promise chain with + * `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user + * elects to use a nodeback, the result will be sent there. If they do not + * pass a nodeback, they will receive the result promise. + * @param object a result (or a promise for a result) + * @param {Function} nodeback a Node.js-style callback + * @returns either the promise or nothing + */ +Q.nodeify = nodeify; +function nodeify(object, nodeback) { + return Q(object).nodeify(nodeback); +} + +Promise.prototype.nodeify = function (nodeback) { + if (nodeback) { + this.then(function (value) { + nextTick(function () { + nodeback(null, value); + }); + }, function (error) { + nextTick(function () { + nodeback(error); + }); + }); + } else { + return this; + } +}; + +// All code before this point will be filtered from stack traces. +var qEndingLine = captureLine(); + +return Q; + +}); diff --git a/StoneIsland/platforms/ios/cordova/node_modules/q/queue.js b/StoneIsland/platforms/ios/cordova/node_modules/q/queue.js new file mode 100755 index 00000000..1505fd0b --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/q/queue.js @@ -0,0 +1,35 @@ + +var Q = require("./q"); + +module.exports = Queue; +function Queue() { + var ends = Q.defer(); + var closed = Q.defer(); + return { + put: function (value) { + var next = Q.defer(); + ends.resolve({ + head: value, + tail: next.promise + }); + ends.resolve = next.resolve; + }, + get: function () { + var result = ends.promise.get("head"); + ends.promise = ends.promise.get("tail"); + return result.fail(function (error) { + closed.resolve(error); + throw error; + }); + }, + closed: closed.promise, + close: function (error) { + error = error || new Error("Can't get value from closed queue"); + var end = {head: Q.reject(error)}; + end.tail = end; + ends.resolve(end); + return closed.promise; + } + }; +} + diff --git a/StoneIsland/platforms/ios/cordova/node_modules/shelljs/LICENSE b/StoneIsland/platforms/ios/cordova/node_modules/shelljs/LICENSE new file mode 100755 index 00000000..1b35ee9f --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/shelljs/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2012, Artur Adib <aadib@mozilla.com> +All rights reserved. + +You may use this project under the terms of the New BSD license as follows: + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Artur Adib nor the + names of the contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/StoneIsland/platforms/ios/cordova/node_modules/shelljs/package.json b/StoneIsland/platforms/ios/cordova/node_modules/shelljs/package.json new file mode 100755 index 00000000..674a1ffb --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/shelljs/package.json @@ -0,0 +1,48 @@ +{ + "name": "shelljs", + "version": "0.1.4", + "author": { + "name": "Artur Adib", + "email": "aadib@mozilla.com" + }, + "description": "Portable Unix shell commands for Node.js", + "keywords": [ + "unix", + "shell", + "makefile", + "make", + "jake", + "synchronous" + ], + "repository": { + "type": "git", + "url": "git://github.com/arturadib/shelljs.git" + }, + "homepage": "http://github.com/arturadib/shelljs", + "main": "./shell.js", + "scripts": { + "test": "node scripts/run-tests" + }, + "bin": { + "shjs": "./bin/shjs" + }, + "dependencies": {}, + "devDependencies": { + "jshint": "~1.1.0" + }, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "readme": "# ShellJS - Unix shell commands for Node.js [](http://travis-ci.org/arturadib/shelljs)\n\nShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!\n\nThe project is [unit-tested](http://travis-ci.org/arturadib/shelljs) and battled-tested in projects like:\n\n+ [PDF.js](http://github.com/mozilla/pdf.js) - Firefox's next-gen PDF reader\n+ [Firebug](http://getfirebug.com/) - Firefox's infamous debugger\n+ [JSHint](http://jshint.com) - Most popular JavaScript linter\n+ [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers\n+ [Yeoman](http://yeoman.io/) - Web application stack and development tool\n+ [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation\n\nand [many more](https://npmjs.org/browse/depended/shelljs).\n\n## Installing\n\nVia npm:\n\n```bash\n$ npm install [-g] shelljs\n```\n\nIf the global option `-g` is specified, the binary `shjs` will be installed. This makes it possible to\nrun ShellJS scripts much like any shell script from the command line, i.e. without requiring a `node_modules` folder:\n\n```bash\n$ shjs my_script\n```\n\nYou can also just copy `shell.js` into your project's directory, and `require()` accordingly.\n\n\n## Examples\n\n### JavaScript\n\n```javascript\nrequire('shelljs/global');\n\nif (!which('git')) {\n echo('Sorry, this script requires git');\n exit(1);\n}\n\n// Copy files to release dir\nmkdir('-p', 'out/Release');\ncp('-R', 'stuff/*', 'out/Release');\n\n// Replace macros in each .js file\ncd('lib');\nls('*.js').forEach(function(file) {\n sed('-i', 'BUILD_VERSION', 'v0.1.2', file);\n sed('-i', /.*REMOVE_THIS_LINE.*\\n/, '', file);\n sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\\n/, cat('macro.js'), file);\n});\ncd('..');\n\n// Run external tool synchronously\nif (exec('git commit -am \"Auto-commit\"').code !== 0) {\n echo('Error: Git commit failed');\n exit(1);\n}\n```\n\n### CoffeeScript\n\n```coffeescript\nrequire 'shelljs/global'\n\nif not which 'git'\n echo 'Sorry, this script requires git'\n exit 1\n\n# Copy files to release dir\nmkdir '-p', 'out/Release'\ncp '-R', 'stuff/*', 'out/Release'\n\n# Replace macros in each .js file\ncd 'lib'\nfor file in ls '*.js'\n sed '-i', 'BUILD_VERSION', 'v0.1.2', file\n sed '-i', /.*REMOVE_THIS_LINE.*\\n/, '', file\n sed '-i', /.*REPLACE_LINE_WITH_MACRO.*\\n/, cat 'macro.js', file\ncd '..'\n\n# Run external tool synchronously\nif (exec 'git commit -am \"Auto-commit\"').code != 0\n echo 'Error: Git commit failed'\n exit 1\n```\n\n## Global vs. Local\n\nThe example above uses the convenience script `shelljs/global` to reduce verbosity. If polluting your global namespace is not desirable, simply require `shelljs`.\n\nExample:\n\n```javascript\nvar shell = require('shelljs');\nshell.echo('hello world');\n```\n\n## Make tool\n\nA convenience script `shelljs/make` is also provided to mimic the behavior of a Unix Makefile. In this case all shell objects are global, and command line arguments will cause the script to execute only the corresponding function in the global `target` object. To avoid redundant calls, target functions are executed only once per script.\n\nExample (CoffeeScript):\n\n```coffeescript\nrequire 'shelljs/make'\n\ntarget.all = ->\n target.bundle()\n target.docs()\n\ntarget.bundle = ->\n cd __dirname\n mkdir 'build'\n cd 'lib'\n (cat '*.js').to '../build/output.js'\n\ntarget.docs = ->\n cd __dirname\n mkdir 'docs'\n cd 'lib'\n for file in ls '*.js'\n text = grep '//@', file # extract special comments\n text.replace '//@', '' # remove comment tags\n text.to 'docs/my_docs.md'\n```\n\nTo run the target `all`, call the above script without arguments: `$ node make`. To run the target `docs`: `$ node make docs`, and so on.\n\n\n\n<!-- \n\n DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED\n\n-->\n\n\n## Command reference\n\n\nAll commands run synchronously, unless otherwise stated.\n\n\n### cd('dir')\nChanges to directory `dir` for the duration of the script\n\n### pwd()\nReturns the current directory.\n\n### ls([options ,] path [,path ...])\n### ls([options ,] path_array)\nAvailable options:\n\n+ `-R`: recursive\n+ `-A`: all files (include files beginning with `.`, except for `.` and `..`)\n\nExamples:\n\n```javascript\nls('projs/*.js');\nls('-R', '/users/me', '/tmp');\nls('-R', ['/users/me', '/tmp']); // same as above\n```\n\nReturns array of files in the given path, or in current directory if no path provided.\n\n### find(path [,path ...])\n### find(path_array)\nExamples:\n\n```javascript\nfind('src', 'lib');\nfind(['src', 'lib']); // same as above\nfind('.').filter(function(file) { return file.match(/\\.js$/); });\n```\n\nReturns array of all files (however deep) in the given paths.\n\nThe main difference from `ls('-R', path)` is that the resulting file names\ninclude the base directories, e.g. `lib/resources/file1` instead of just `file1`.\n\n### cp([options ,] source [,source ...], dest)\n### cp([options ,] source_array, dest)\nAvailable options:\n\n+ `-f`: force\n+ `-r, -R`: recursive\n\nExamples:\n\n```javascript\ncp('file1', 'dir1');\ncp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp');\ncp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above\n```\n\nCopies files. The wildcard `*` is accepted.\n\n### rm([options ,] file [, file ...])\n### rm([options ,] file_array)\nAvailable options:\n\n+ `-f`: force\n+ `-r, -R`: recursive\n\nExamples:\n\n```javascript\nrm('-rf', '/tmp/*');\nrm('some_file.txt', 'another_file.txt');\nrm(['some_file.txt', 'another_file.txt']); // same as above\n```\n\nRemoves files. The wildcard `*` is accepted.\n\n### mv(source [, source ...], dest')\n### mv(source_array, dest')\nAvailable options:\n\n+ `f`: force\n\nExamples:\n\n```javascript\nmv('-f', 'file', 'dir/');\nmv('file1', 'file2', 'dir/');\nmv(['file1', 'file2'], 'dir/'); // same as above\n```\n\nMoves files. The wildcard `*` is accepted.\n\n### mkdir([options ,] dir [, dir ...])\n### mkdir([options ,] dir_array)\nAvailable options:\n\n+ `p`: full path (will create intermediate dirs if necessary)\n\nExamples:\n\n```javascript\nmkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g');\nmkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above\n```\n\nCreates directories.\n\n### test(expression)\nAvailable expression primaries:\n\n+ `'-b', 'path'`: true if path is a block device\n+ `'-c', 'path'`: true if path is a character device\n+ `'-d', 'path'`: true if path is a directory\n+ `'-e', 'path'`: true if path exists\n+ `'-f', 'path'`: true if path is a regular file\n+ `'-L', 'path'`: true if path is a symbolic link\n+ `'-p', 'path'`: true if path is a pipe (FIFO)\n+ `'-S', 'path'`: true if path is a socket\n\nExamples:\n\n```javascript\nif (test('-d', path)) { /* do something with dir */ };\nif (!test('-f', path)) continue; // skip if it's a regular file\n```\n\nEvaluates expression using the available primaries and returns corresponding value.\n\n### cat(file [, file ...])\n### cat(file_array)\n\nExamples:\n\n```javascript\nvar str = cat('file*.txt');\nvar str = cat('file1', 'file2');\nvar str = cat(['file1', 'file2']); // same as above\n```\n\nReturns a string containing the given file, or a concatenated string\ncontaining the files if more than one file is given (a new line character is\nintroduced between each file). Wildcard `*` accepted.\n\n### 'string'.to(file)\n\nExamples:\n\n```javascript\ncat('input.txt').to('output.txt');\n```\n\nAnalogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as\nthose returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_\n\n### sed([options ,] search_regex, replace_str, file)\nAvailable options:\n\n+ `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_\n\nExamples:\n\n```javascript\nsed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');\nsed(/.*DELETE_THIS_LINE.*\\n/, '', 'source.js');\n```\n\nReads an input string from `file` and performs a JavaScript `replace()` on the input\nusing the given search regex and replacement string. Returns the new string after replacement.\n\n### grep([options ,] regex_filter, file [, file ...])\n### grep([options ,] regex_filter, file_array)\nAvailable options:\n\n+ `-v`: Inverse the sense of the regex and print the lines not matching the criteria.\n\nExamples:\n\n```javascript\ngrep('-v', 'GLOBAL_VARIABLE', '*.js');\ngrep('GLOBAL_VARIABLE', '*.js');\n```\n\nReads input string from given files and returns a string containing all lines of the\nfile that match the given `regex_filter`. Wildcard `*` accepted.\n\n### which(command)\n\nExamples:\n\n```javascript\nvar nodeExec = which('node');\n```\n\nSearches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions.\nReturns string containing the absolute path to the command.\n\n### echo(string [,string ...])\n\nExamples:\n\n```javascript\necho('hello world');\nvar str = echo('hello world');\n```\n\nPrints string to stdout, and returns string with additional utility methods\nlike `.to()`.\n\n### dirs([options | '+N' | '-N'])\n\nAvailable options:\n\n+ `-c`: Clears the directory stack by deleting all of the elements.\n\nArguments:\n\n+ `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.\n+ `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.\n\nDisplay the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified.\n\nSee also: pushd, popd\n\n### pushd([options,] [dir | '-N' | '+N'])\n\nAvailable options:\n\n+ `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated.\n\nArguments:\n\n+ `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`.\n+ `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.\n+ `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.\n\nExamples:\n\n```javascript\n// process.cwd() === '/usr'\npushd('/etc'); // Returns /etc /usr\npushd('+1'); // Returns /usr /etc\n```\n\nSave the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack.\n\n### popd([options,] ['-N' | '+N'])\n\nAvailable options:\n\n+ `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated.\n\nArguments:\n\n+ `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero.\n+ `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero.\n\nExamples:\n\n```javascript\necho(process.cwd()); // '/usr'\npushd('/etc'); // '/etc /usr'\necho(process.cwd()); // '/etc'\npopd(); // '/usr'\necho(process.cwd()); // '/usr'\n```\n\nWhen no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack.\n\n### exit(code)\nExits the current process with the given exit code.\n\n### env['VAR_NAME']\nObject containing environment variables (both getter and setter). Shortcut to process.env.\n\n### exec(command [, options] [, callback])\nAvailable options (all `false` by default):\n\n+ `async`: Asynchronous execution. Defaults to true if a callback is provided.\n+ `silent`: Do not echo program output to console.\n\nExamples:\n\n```javascript\nvar version = exec('node --version', {silent:true}).output;\n\nvar child = exec('some_long_running_process', {async:true});\nchild.stdout.on('data', function(data) {\n /* ... do something with data ... */\n});\n\nexec('some_long_running_process', function(code, output) {\n console.log('Exit code:', code);\n console.log('Program output:', output);\n});\n```\n\nExecutes the given `command` _synchronously_, unless otherwise specified.\nWhen in synchronous mode returns the object `{ code:..., output:... }`, containing the program's\n`output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and\nthe `callback` gets the arguments `(code, output)`.\n\n**Note:** For long-lived processes, it's best to run `exec()` asynchronously as\nthe current synchronous implementation uses a lot of CPU. This should be getting\nfixed soon.\n\n### chmod(octal_mode || octal_string, file)\n### chmod(symbolic_mode, file)\n\nAvailable options:\n\n+ `-v`: output a diagnostic for every file processed\n+ `-c`: like verbose but report only when a change is made\n+ `-R`: change files and directories recursively\n\nExamples:\n\n```javascript\nchmod(755, '/Users/brandon');\nchmod('755', '/Users/brandon'); // same as above \nchmod('u+x', '/Users/brandon');\n```\n\nAlters the permissions of a file or directory by either specifying the\nabsolute permissions in octal form or expressing the changes in symbols.\nThis command tries to mimic the POSIX behavior as much as possible.\nNotable exceptions:\n\n+ In symbolic modes, 'a-r' and '-r' are identical. No consideration is\n given to the umask.\n+ There is no \"quiet\" option since default behavior is to run silent.\n\n## Configuration\n\n\n### config.silent\nExample:\n\n```javascript\nvar silentState = config.silent; // save old silent state\nconfig.silent = true;\n/* ... */\nconfig.silent = silentState; // restore old silent state\n```\n\nSuppresses all command output if `true`, except for `echo()` calls.\nDefault is `false`.\n\n### config.fatal\nExample:\n\n```javascript\nconfig.fatal = true;\ncp('this_file_does_not_exist', '/dev/null'); // dies here\n/* more commands... */\n```\n\nIf `true` the script will die on errors. Default is `false`.\n\n## Non-Unix commands\n\n\n### tempdir()\nSearches and returns string containing a writeable, platform-dependent temporary directory.\nFollows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir).\n\n### error()\nTests if error occurred in the last command. Returns `null` if no error occurred,\notherwise returns string explaining the error\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/arturadib/shelljs/issues" + }, + "_id": "shelljs@0.1.4", + "dist": { + "shasum": "7a8aeaa3dc3c0be2e59d83168e83b4c4bc4dac95" + }, + "_from": "shelljs@0.1.4", + "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.1.4.tgz" +} diff --git a/StoneIsland/platforms/ios/cordova/node_modules/shelljs/shell.js b/StoneIsland/platforms/ios/cordova/node_modules/shelljs/shell.js new file mode 100755 index 00000000..4190aa34 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/node_modules/shelljs/shell.js @@ -0,0 +1,1901 @@ +// +// ShellJS +// Unix shell commands on top of Node's API +// +// Copyright (c) 2012 Artur Adib +// http://github.com/arturadib/shelljs +// + +var fs = require('fs'), + path = require('path'), + util = require('util'), + vm = require('vm'), + child = require('child_process'), + os = require('os'); + +// Node shims for < v0.7 +fs.existsSync = fs.existsSync || path.existsSync; + +var config = { + silent: false, + fatal: false +}; + +var state = { + error: null, + currentCmd: 'shell.js', + tempDir: null + }, + platform = os.type().match(/^Win/) ? 'win' : 'unix'; + + +//@ +//@ All commands run synchronously, unless otherwise stated. +//@ + + +//@ +//@ ### cd('dir') +//@ Changes to directory `dir` for the duration of the script +function _cd(options, dir) { + if (!dir) + error('directory not specified'); + + if (!fs.existsSync(dir)) + error('no such file or directory: ' + dir); + + if (!fs.statSync(dir).isDirectory()) + error('not a directory: ' + dir); + + process.chdir(dir); +} +exports.cd = wrap('cd', _cd); + +//@ +//@ ### pwd() +//@ Returns the current directory. +function _pwd(options) { + var pwd = path.resolve(process.cwd()); + return ShellString(pwd); +} +exports.pwd = wrap('pwd', _pwd); + + +//@ +//@ ### ls([options ,] path [,path ...]) +//@ ### ls([options ,] path_array) +//@ Available options: +//@ +//@ + `-R`: recursive +//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ ls('projs/*.js'); +//@ ls('-R', '/users/me', '/tmp'); +//@ ls('-R', ['/users/me', '/tmp']); // same as above +//@ ``` +//@ +//@ Returns array of files in the given path, or in current directory if no path provided. +function _ls(options, paths) { + options = parseOptions(options, { + 'R': 'recursive', + 'A': 'all', + 'a': 'all_deprecated' + }); + + if (options.all_deprecated) { + // We won't support the -a option as it's hard to image why it's useful + // (it includes '.' and '..' in addition to '.*' files) + // For backwards compatibility we'll dump a deprecated message and proceed as before + log('ls: Option -a is deprecated. Use -A instead'); + options.all = true; + } + + if (!paths) + paths = ['.']; + else if (typeof paths === 'object') + paths = paths; // assume array + else if (typeof paths === 'string') + paths = [].slice.call(arguments, 1); + + var list = []; + + // Conditionally pushes file to list - returns true if pushed, false otherwise + // (e.g. prevents hidden files to be included unless explicitly told so) + function pushFile(file, query) { + // hidden file? + if (path.basename(file)[0] === '.') { + // not explicitly asking for hidden files? + if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1)) + return false; + } + + if (platform === 'win') + file = file.replace(/\\/g, '/'); + + list.push(file); + return true; + } + + paths.forEach(function(p) { + if (fs.existsSync(p)) { + var stats = fs.statSync(p); + // Simple file? + if (stats.isFile()) { + pushFile(p, p); + return; // continue + } + + // Simple dir? + if (stats.isDirectory()) { + // Iterate over p contents + fs.readdirSync(p).forEach(function(file) { + if (!pushFile(file, p)) + return; + + // Recursive? + if (options.recursive) { + var oldDir = _pwd(); + _cd('', p); + if (fs.statSync(file).isDirectory()) + list = list.concat(_ls('-R'+(options.all?'A':''), file+'/*')); + _cd('', oldDir); + } + }); + return; // continue + } + } + + // p does not exist - possible wildcard present + + var basename = path.basename(p); + var dirname = path.dirname(p); + // Wildcard present on an existing dir? (e.g. '/tmp/*.js') + if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) { + // Escape special regular expression chars + var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1'); + // Translates wildcard into regex + regexp = '^' + regexp.replace(/\*/g, '.*') + '$'; + // Iterate over directory contents + fs.readdirSync(dirname).forEach(function(file) { + if (file.match(new RegExp(regexp))) { + if (!pushFile(path.normalize(dirname+'/'+file), basename)) + return; + + // Recursive? + if (options.recursive) { + var pp = dirname + '/' + file; + if (fs.lstatSync(pp).isDirectory()) + list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*')); + } // recursive + } // if file matches + }); // forEach + return; + } + + error('no such file or directory: ' + p, true); + }); + + return list; +} +exports.ls = wrap('ls', _ls); + + +//@ +//@ ### find(path [,path ...]) +//@ ### find(path_array) +//@ Examples: +//@ +//@ ```javascript +//@ find('src', 'lib'); +//@ find(['src', 'lib']); // same as above +//@ find('.').filter(function(file) { return file.match(/\.js$/); }); +//@ ``` +//@ +//@ Returns array of all files (however deep) in the given paths. +//@ +//@ The main difference from `ls('-R', path)` is that the resulting file names +//@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`. +function _find(options, paths) { + if (!paths) + error('no path specified'); + else if (typeof paths === 'object') + paths = paths; // assume array + else if (typeof paths === 'string') + paths = [].slice.call(arguments, 1); + + var list = []; + + function pushFile(file) { + if (platform === 'win') + file = file.replace(/\\/g, '/'); + list.push(file); + } + + // why not simply do ls('-R', paths)? because the output wouldn't give the base dirs + // to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory + + paths.forEach(function(file) { + pushFile(file); + + if (fs.statSync(file).isDirectory()) { + _ls('-RA', file+'/*').forEach(function(subfile) { + pushFile(subfile); + }); + } + }); + + return list; +} +exports.find = wrap('find', _find); + + +//@ +//@ ### cp([options ,] source [,source ...], dest) +//@ ### cp([options ,] source_array, dest) +//@ Available options: +//@ +//@ + `-f`: force +//@ + `-r, -R`: recursive +//@ +//@ Examples: +//@ +//@ ```javascript +//@ cp('file1', 'dir1'); +//@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); +//@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above +//@ ``` +//@ +//@ Copies files. The wildcard `*` is accepted. +function _cp(options, sources, dest) { + options = parseOptions(options, { + 'f': 'force', + 'R': 'recursive', + 'r': 'recursive' + }); + + // Get sources, dest + if (arguments.length < 3) { + error('missing <source> and/or <dest>'); + } else if (arguments.length > 3) { + sources = [].slice.call(arguments, 1, arguments.length - 1); + dest = arguments[arguments.length - 1]; + } else if (typeof sources === 'string') { + sources = [sources]; + } else if ('length' in sources) { + sources = sources; // no-op for array + } else { + error('invalid arguments'); + } + + var exists = fs.existsSync(dest), + stats = exists && fs.statSync(dest); + + // Dest is not existing dir, but multiple sources given + if ((!exists || !stats.isDirectory()) && sources.length > 1) + error('dest is not a directory (too many sources)'); + + // Dest is an existing file, but no -f given + if (exists && stats.isFile() && !options.force) + error('dest file already exists: ' + dest); + + if (options.recursive) { + // Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*" + // (see Github issue #15) + sources.forEach(function(src, i) { + if (src[src.length - 1] === '/') + sources[i] += '*'; + }); + + // Create dest + try { + fs.mkdirSync(dest, parseInt('0777', 8)); + } catch (e) { + // like Unix's cp, keep going even if we can't create dest dir + } + } + + sources = expand(sources); + + sources.forEach(function(src) { + if (!fs.existsSync(src)) { + error('no such file or directory: '+src, true); + return; // skip file + } + + // If here, src exists + if (fs.statSync(src).isDirectory()) { + if (!options.recursive) { + // Non-Recursive + log(src + ' is a directory (not copied)'); + } else { + // Recursive + // 'cp /a/source dest' should create 'source' in 'dest' + var newDest = path.join(dest, path.basename(src)), + checkDir = fs.statSync(src); + try { + fs.mkdirSync(newDest, checkDir.mode); + } catch (e) { + //if the directory already exists, that's okay + if (e.code !== 'EEXIST') throw e; + } + + cpdirSyncRecursive(src, newDest, {force: options.force}); + } + return; // done with dir + } + + // If here, src is a file + + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) + thisDest = path.normalize(dest + '/' + path.basename(src)); + + if (fs.existsSync(thisDest) && !options.force) { + error('dest file already exists: ' + thisDest, true); + return; // skip file + } + + copyFileSync(src, thisDest); + }); // forEach(src) +} +exports.cp = wrap('cp', _cp); + +//@ +//@ ### rm([options ,] file [, file ...]) +//@ ### rm([options ,] file_array) +//@ Available options: +//@ +//@ + `-f`: force +//@ + `-r, -R`: recursive +//@ +//@ Examples: +//@ +//@ ```javascript +//@ rm('-rf', '/tmp/*'); +//@ rm('some_file.txt', 'another_file.txt'); +//@ rm(['some_file.txt', 'another_file.txt']); // same as above +//@ ``` +//@ +//@ Removes files. The wildcard `*` is accepted. +function _rm(options, files) { + options = parseOptions(options, { + 'f': 'force', + 'r': 'recursive', + 'R': 'recursive' + }); + if (!files) + error('no paths given'); + + if (typeof files === 'string') + files = [].slice.call(arguments, 1); + // if it's array leave it as it is + + files = expand(files); + + files.forEach(function(file) { + if (!fs.existsSync(file)) { + // Path does not exist, no force flag given + if (!options.force) + error('no such file or directory: '+file, true); + + return; // skip file + } + + // If here, path exists + + var stats = fs.statSync(file); + // Remove simple file + if (stats.isFile()) { + + // Do not check for file writing permissions + if (options.force) { + _unlinkSync(file); + return; + } + + if (isWriteable(file)) + _unlinkSync(file); + else + error('permission denied: '+file, true); + + return; + } // simple file + + // Path is an existing directory, but no -r flag given + if (stats.isDirectory() && !options.recursive) { + error('path is a directory', true); + return; // skip path + } + + // Recursively remove existing directory + if (stats.isDirectory() && options.recursive) { + rmdirSyncRecursive(file, options.force); + } + }); // forEach(file) +} // rm +exports.rm = wrap('rm', _rm); + +//@ +//@ ### mv(source [, source ...], dest') +//@ ### mv(source_array, dest') +//@ Available options: +//@ +//@ + `f`: force +//@ +//@ Examples: +//@ +//@ ```javascript +//@ mv('-f', 'file', 'dir/'); +//@ mv('file1', 'file2', 'dir/'); +//@ mv(['file1', 'file2'], 'dir/'); // same as above +//@ ``` +//@ +//@ Moves files. The wildcard `*` is accepted. +function _mv(options, sources, dest) { + options = parseOptions(options, { + 'f': 'force' + }); + + // Get sources, dest + if (arguments.length < 3) { + error('missing <source> and/or <dest>'); + } else if (arguments.length > 3) { + sources = [].slice.call(arguments, 1, arguments.length - 1); + dest = arguments[arguments.length - 1]; + } else if (typeof sources === 'string') { + sources = [sources]; + } else if ('length' in sources) { + sources = sources; // no-op for array + } else { + error('invalid arguments'); + } + + sources = expand(sources); + + var exists = fs.existsSync(dest), + stats = exists && fs.statSync(dest); + + // Dest is not existing dir, but multiple sources given + if ((!exists || !stats.isDirectory()) && sources.length > 1) + error('dest is not a directory (too many sources)'); + + // Dest is an existing file, but no -f given + if (exists && stats.isFile() && !options.force) + error('dest file already exists: ' + dest); + + sources.forEach(function(src) { + if (!fs.existsSync(src)) { + error('no such file or directory: '+src, true); + return; // skip file + } + + // If here, src exists + + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) + thisDest = path.normalize(dest + '/' + path.basename(src)); + + if (fs.existsSync(thisDest) && !options.force) { + error('dest file already exists: ' + thisDest, true); + return; // skip file + } + + if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { + error('cannot move to self: '+src, true); + return; // skip file + } + + fs.renameSync(src, thisDest); + }); // forEach(src) +} // mv +exports.mv = wrap('mv', _mv); + +//@ +//@ ### mkdir([options ,] dir [, dir ...]) +//@ ### mkdir([options ,] dir_array) +//@ Available options: +//@ +//@ + `p`: full path (will create intermediate dirs if necessary) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); +//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above +//@ ``` +//@ +//@ Creates directories. +function _mkdir(options, dirs) { + options = parseOptions(options, { + 'p': 'fullpath' + }); + if (!dirs) + error('no paths given'); + + if (typeof dirs === 'string') + dirs = [].slice.call(arguments, 1); + // if it's array leave it as it is + + dirs.forEach(function(dir) { + if (fs.existsSync(dir)) { + if (!options.fullpath) + error('path already exists: ' + dir, true); + return; // skip dir + } + + // Base dir does not exist, and no -p option given + var baseDir = path.dirname(dir); + if (!fs.existsSync(baseDir) && !options.fullpath) { + error('no such file or directory: ' + baseDir, true); + return; // skip dir + } + + if (options.fullpath) + mkdirSyncRecursive(dir); + else + fs.mkdirSync(dir, parseInt('0777', 8)); + }); +} // mkdir +exports.mkdir = wrap('mkdir', _mkdir); + +//@ +//@ ### test(expression) +//@ Available expression primaries: +//@ +//@ + `'-b', 'path'`: true if path is a block device +//@ + `'-c', 'path'`: true if path is a character device +//@ + `'-d', 'path'`: true if path is a directory +//@ + `'-e', 'path'`: true if path exists +//@ + `'-f', 'path'`: true if path is a regular file +//@ + `'-L', 'path'`: true if path is a symbolic link +//@ + `'-p', 'path'`: true if path is a pipe (FIFO) +//@ + `'-S', 'path'`: true if path is a socket +//@ +//@ Examples: +//@ +//@ ```javascript +//@ if (test('-d', path)) { /* do something with dir */ }; +//@ if (!test('-f', path)) continue; // skip if it's a regular file +//@ ``` +//@ +//@ Evaluates expression using the available primaries and returns corresponding value. +function _test(options, path) { + if (!path) + error('no path given'); + + // hack - only works with unary primaries + options = parseOptions(options, { + 'b': 'block', + 'c': 'character', + 'd': 'directory', + 'e': 'exists', + 'f': 'file', + 'L': 'link', + 'p': 'pipe', + 'S': 'socket' + }); + + var canInterpret = false; + for (var key in options) + if (options[key] === true) { + canInterpret = true; + break; + } + + if (!canInterpret) + error('could not interpret expression'); + + if (options.link) { + try { + return fs.lstatSync(path).isSymbolicLink(); + } catch(e) { + return false; + } + } + + if (!fs.existsSync(path)) + return false; + + if (options.exists) + return true; + + var stats = fs.statSync(path); + + if (options.block) + return stats.isBlockDevice(); + + if (options.character) + return stats.isCharacterDevice(); + + if (options.directory) + return stats.isDirectory(); + + if (options.file) + return stats.isFile(); + + if (options.pipe) + return stats.isFIFO(); + + if (options.socket) + return stats.isSocket(); +} // test +exports.test = wrap('test', _test); + + +//@ +//@ ### cat(file [, file ...]) +//@ ### cat(file_array) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = cat('file*.txt'); +//@ var str = cat('file1', 'file2'); +//@ var str = cat(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Returns a string containing the given file, or a concatenated string +//@ containing the files if more than one file is given (a new line character is +//@ introduced between each file). Wildcard `*` accepted. +function _cat(options, files) { + var cat = ''; + + if (!files) + error('no paths given'); + + if (typeof files === 'string') + files = [].slice.call(arguments, 1); + // if it's array leave it as it is + + files = expand(files); + + files.forEach(function(file) { + if (!fs.existsSync(file)) + error('no such file or directory: ' + file); + + cat += fs.readFileSync(file, 'utf8') + '\n'; + }); + + if (cat[cat.length-1] === '\n') + cat = cat.substring(0, cat.length-1); + + return ShellString(cat); +} +exports.cat = wrap('cat', _cat); + +//@ +//@ ### 'string'.to(file) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ cat('input.txt').to('output.txt'); +//@ ``` +//@ +//@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as +//@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ +function _to(options, file) { + if (!file) + error('wrong arguments'); + + if (!fs.existsSync( path.dirname(file) )) + error('no such file or directory: ' + path.dirname(file)); + + try { + fs.writeFileSync(file, this.toString(), 'utf8'); + } catch(e) { + error('could not write to file (code '+e.code+'): '+file, true); + } +} +// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings. +// For now, this is a dummy function to bookmark places we need such strings +function ShellString(str) { + return str; +} +String.prototype.to = wrap('to', _to); + +//@ +//@ ### sed([options ,] search_regex, replace_str, file) +//@ Available options: +//@ +//@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_ +//@ +//@ Examples: +//@ +//@ ```javascript +//@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); +//@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); +//@ ``` +//@ +//@ Reads an input string from `file` and performs a JavaScript `replace()` on the input +//@ using the given search regex and replacement string. Returns the new string after replacement. +function _sed(options, regex, replacement, file) { + options = parseOptions(options, { + 'i': 'inplace' + }); + + if (typeof replacement === 'string') + replacement = replacement; // no-op + else if (typeof replacement === 'number') + replacement = replacement.toString(); // fallback + else + error('invalid replacement string'); + + if (!file) + error('no file given'); + + if (!fs.existsSync(file)) + error('no such file or directory: ' + file); + + var result = fs.readFileSync(file, 'utf8').replace(regex, replacement); + if (options.inplace) + fs.writeFileSync(file, result, 'utf8'); + + return ShellString(result); +} +exports.sed = wrap('sed', _sed); + +//@ +//@ ### grep([options ,] regex_filter, file [, file ...]) +//@ ### grep([options ,] regex_filter, file_array) +//@ Available options: +//@ +//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); +//@ grep('GLOBAL_VARIABLE', '*.js'); +//@ ``` +//@ +//@ Reads input string from given files and returns a string containing all lines of the +//@ file that match the given `regex_filter`. Wildcard `*` accepted. +function _grep(options, regex, files) { + options = parseOptions(options, { + 'v': 'inverse' + }); + + if (!files) + error('no paths given'); + + if (typeof files === 'string') + files = [].slice.call(arguments, 2); + // if it's array leave it as it is + + files = expand(files); + + var grep = ''; + files.forEach(function(file) { + if (!fs.existsSync(file)) { + error('no such file or directory: ' + file, true); + return; + } + + var contents = fs.readFileSync(file, 'utf8'), + lines = contents.split(/\r*\n/); + lines.forEach(function(line) { + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) + grep += line + '\n'; + }); + }); + + return ShellString(grep); +} +exports.grep = wrap('grep', _grep); + + +//@ +//@ ### which(command) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var nodeExec = which('node'); +//@ ``` +//@ +//@ Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions. +//@ Returns string containing the absolute path to the command. +function _which(options, cmd) { + if (!cmd) + error('must specify command'); + + var pathEnv = process.env.path || process.env.Path || process.env.PATH, + pathArray = splitPath(pathEnv), + where = null; + + // No relative/absolute paths provided? + if (cmd.search(/\//) === -1) { + // Search for command in PATH + pathArray.forEach(function(dir) { + if (where) + return; // already found it + + var attempt = path.resolve(dir + '/' + cmd); + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + + if (platform === 'win') { + var baseAttempt = attempt; + attempt = baseAttempt + '.exe'; + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + attempt = baseAttempt + '.cmd'; + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + attempt = baseAttempt + '.bat'; + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + } // if 'win' + }); + } + + // Command not found anywhere? + if (!fs.existsSync(cmd) && !where) + return null; + + where = where || path.resolve(cmd); + + return ShellString(where); +} +exports.which = wrap('which', _which); + +//@ +//@ ### echo(string [,string ...]) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ echo('hello world'); +//@ var str = echo('hello world'); +//@ ``` +//@ +//@ Prints string to stdout, and returns string with additional utility methods +//@ like `.to()`. +function _echo() { + var messages = [].slice.call(arguments, 0); + console.log.apply(this, messages); + return ShellString(messages.join(' ')); +} +exports.echo = _echo; // don't wrap() as it could parse '-options' + +// Pushd/popd/dirs internals +var _dirStack = []; + +function _isStackIndex(index) { + return (/^[\-+]\d+$/).test(index); +} + +function _parseStackIndex(index) { + if (_isStackIndex(index)) { + if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd + return (/^-/).test(index) ? Number(index) - 1 : Number(index); + } else { + error(index + ': directory stack index out of range'); + } + } else { + error(index + ': invalid number'); + } +} + +function _actualDirStack() { + return [process.cwd()].concat(_dirStack); +} + +//@ +//@ ### dirs([options | '+N' | '-N']) +//@ +//@ Available options: +//@ +//@ + `-c`: Clears the directory stack by deleting all of the elements. +//@ +//@ Arguments: +//@ +//@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. +//@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. +//@ +//@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. +//@ +//@ See also: pushd, popd +function _dirs(options, index) { + if (_isStackIndex(options)) { + index = options; + options = ''; + } + + options = parseOptions(options, { + 'c' : 'clear' + }); + + if (options['clear']) { + _dirStack = []; + return _dirStack; + } + + var stack = _actualDirStack(); + + if (index) { + index = _parseStackIndex(index); + + if (index < 0) { + index = stack.length + index; + } + + log(stack[index]); + return stack[index]; + } + + log(stack.join(' ')); + + return stack; +} +exports.dirs = wrap("dirs", _dirs); + +//@ +//@ ### pushd([options,] [dir | '-N' | '+N']) +//@ +//@ Available options: +//@ +//@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. +//@ +//@ Arguments: +//@ +//@ + `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`. +//@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. +//@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ // process.cwd() === '/usr' +//@ pushd('/etc'); // Returns /etc /usr +//@ pushd('+1'); // Returns /usr /etc +//@ ``` +//@ +//@ Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. +function _pushd(options, dir) { + if (_isStackIndex(options)) { + dir = options; + options = ''; + } + + options = parseOptions(options, { + 'n' : 'no-cd' + }); + + var dirs = _actualDirStack(); + + if (dir === '+0') { + return dirs; // +0 is a noop + } else if (!dir) { + if (dirs.length > 1) { + dirs = dirs.splice(1, 1).concat(dirs); + } else { + return error('no other directory'); + } + } else if (_isStackIndex(dir)) { + var n = _parseStackIndex(dir); + dirs = dirs.slice(n).concat(dirs.slice(0, n)); + } else { + if (options['no-cd']) { + dirs.splice(1, 0, dir); + } else { + dirs.unshift(dir); + } + } + + if (options['no-cd']) { + dirs = dirs.slice(1); + } else { + dir = path.resolve(dirs.shift()); + _cd('', dir); + } + + _dirStack = dirs; + return _dirs(''); +} +exports.pushd = wrap('pushd', _pushd); + +//@ +//@ ### popd([options,] ['-N' | '+N']) +//@ +//@ Available options: +//@ +//@ + `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. +//@ +//@ Arguments: +//@ +//@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. +//@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ echo(process.cwd()); // '/usr' +//@ pushd('/etc'); // '/etc /usr' +//@ echo(process.cwd()); // '/etc' +//@ popd(); // '/usr' +//@ echo(process.cwd()); // '/usr' +//@ ``` +//@ +//@ When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. +function _popd(options, index) { + if (_isStackIndex(options)) { + index = options; + options = ''; + } + + options = parseOptions(options, { + 'n' : 'no-cd' + }); + + if (!_dirStack.length) { + return error('directory stack empty'); + } + + index = _parseStackIndex(index || '+0'); + + if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) { + index = index > 0 ? index - 1 : index; + _dirStack.splice(index, 1); + } else { + var dir = path.resolve(_dirStack.shift()); + _cd('', dir); + } + + return _dirs(''); +} +exports.popd = wrap("popd", _popd); + +//@ +//@ ### exit(code) +//@ Exits the current process with the given exit code. +exports.exit = process.exit; + +//@ +//@ ### env['VAR_NAME'] +//@ Object containing environment variables (both getter and setter). Shortcut to process.env. +exports.env = process.env; + +//@ +//@ ### exec(command [, options] [, callback]) +//@ Available options (all `false` by default): +//@ +//@ + `async`: Asynchronous execution. Defaults to true if a callback is provided. +//@ + `silent`: Do not echo program output to console. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var version = exec('node --version', {silent:true}).output; +//@ +//@ var child = exec('some_long_running_process', {async:true}); +//@ child.stdout.on('data', function(data) { +//@ /* ... do something with data ... */ +//@ }); +//@ +//@ exec('some_long_running_process', function(code, output) { +//@ console.log('Exit code:', code); +//@ console.log('Program output:', output); +//@ }); +//@ ``` +//@ +//@ Executes the given `command` _synchronously_, unless otherwise specified. +//@ When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's +//@ `output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and +//@ the `callback` gets the arguments `(code, output)`. +//@ +//@ **Note:** For long-lived processes, it's best to run `exec()` asynchronously as +//@ the current synchronous implementation uses a lot of CPU. This should be getting +//@ fixed soon. +function _exec(command, options, callback) { + if (!command) + error('must specify command'); + + // Callback is defined instead of options. + if (typeof options === 'function') { + callback = options; + options = { async: true }; + } + + // Callback is defined with options. + if (typeof options === 'object' && typeof callback === 'function') { + options.async = true; + } + + options = extend({ + silent: config.silent, + async: false + }, options); + + if (options.async) + return execAsync(command, options, callback); + else + return execSync(command, options); +} +exports.exec = wrap('exec', _exec, {notUnix:true}); + +var PERMS = (function (base) { + return { + OTHER_EXEC : base.EXEC, + OTHER_WRITE : base.WRITE, + OTHER_READ : base.READ, + + GROUP_EXEC : base.EXEC << 3, + GROUP_WRITE : base.WRITE << 3, + GROUP_READ : base.READ << 3, + + OWNER_EXEC : base.EXEC << 6, + OWNER_WRITE : base.WRITE << 6, + OWNER_READ : base.READ << 6, + + // Literal octal numbers are apparently not allowed in "strict" javascript. Using parseInt is + // the preferred way, else a jshint warning is thrown. + STICKY : parseInt('01000', 8), + SETGID : parseInt('02000', 8), + SETUID : parseInt('04000', 8), + + TYPE_MASK : parseInt('0770000', 8) + }; +})({ + EXEC : 1, + WRITE : 2, + READ : 4 +}); + + +//@ +//@ ### chmod(octal_mode || octal_string, file) +//@ ### chmod(symbolic_mode, file) +//@ +//@ Available options: +//@ +//@ + `-v`: output a diagnostic for every file processed//@ +//@ + `-c`: like verbose but report only when a change is made//@ +//@ + `-R`: change files and directories recursively//@ +//@ +//@ Examples: +//@ +//@ ```javascript +//@ chmod(755, '/Users/brandon'); +//@ chmod('755', '/Users/brandon'); // same as above +//@ chmod('u+x', '/Users/brandon'); +//@ ``` +//@ +//@ Alters the permissions of a file or directory by either specifying the +//@ absolute permissions in octal form or expressing the changes in symbols. +//@ This command tries to mimic the POSIX behavior as much as possible. +//@ Notable exceptions: +//@ +//@ + In symbolic modes, 'a-r' and '-r' are identical. No consideration is +//@ given to the umask. +//@ + There is no "quiet" option since default behavior is to run silent. +function _chmod(options, mode, filePattern) { + if (!filePattern) { + if (options.length > 0 && options.charAt(0) === '-') { + // Special case where the specified file permissions started with - to subtract perms, which + // get picked up by the option parser as command flags. + // If we are down by one argument and options starts with -, shift everything over. + filePattern = mode; + mode = options; + options = ''; + } + else { + error('You must specify a file.'); + } + } + + options = parseOptions(options, { + 'R': 'recursive', + 'c': 'changes', + 'v': 'verbose' + }); + + if (typeof filePattern === 'string') { + filePattern = [ filePattern ]; + } + + var files; + + if (options.recursive) { + files = []; + expand(filePattern).forEach(function addFile(expandedFile) { + var stat = fs.lstatSync(expandedFile); + + if (!stat.isSymbolicLink()) { + files.push(expandedFile); + + if (stat.isDirectory()) { // intentionally does not follow symlinks. + fs.readdirSync(expandedFile).forEach(function (child) { + addFile(expandedFile + '/' + child); + }); + } + } + }); + } + else { + files = expand(filePattern); + } + + files.forEach(function innerChmod(file) { + file = path.resolve(file); + if (!fs.existsSync(file)) { + error('File not found: ' + file); + } + + // When recursing, don't follow symlinks. + if (options.recursive && fs.lstatSync(file).isSymbolicLink()) { + return; + } + + var perms = fs.statSync(file).mode; + var type = perms & PERMS.TYPE_MASK; + + var newPerms = perms; + + if (isNaN(parseInt(mode, 8))) { + // parse options + mode.split(',').forEach(function (symbolicMode) { + /*jshint regexdash:true */ + var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; + var matches = pattern.exec(symbolicMode); + + if (matches) { + var applyTo = matches[1]; + var operator = matches[2]; + var change = matches[3]; + + var changeOwner = applyTo.indexOf('u') != -1 || applyTo === 'a' || applyTo === ''; + var changeGroup = applyTo.indexOf('g') != -1 || applyTo === 'a' || applyTo === ''; + var changeOther = applyTo.indexOf('o') != -1 || applyTo === 'a' || applyTo === ''; + + var changeRead = change.indexOf('r') != -1; + var changeWrite = change.indexOf('w') != -1; + var changeExec = change.indexOf('x') != -1; + var changeSticky = change.indexOf('t') != -1; + var changeSetuid = change.indexOf('s') != -1; + + var mask = 0; + if (changeOwner) { + mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0); + } + if (changeGroup) { + mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0); + } + if (changeOther) { + mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0); + } + + // Sticky bit is special - it's not tied to user, group or other. + if (changeSticky) { + mask |= PERMS.STICKY; + } + + switch (operator) { + case '+': + newPerms |= mask; + break; + + case '-': + newPerms &= ~mask; + break; + + case '=': + newPerms = type + mask; + + // According to POSIX, when using = to explicitly set the permissions, setuid and setgid can never be cleared. + if (fs.statSync(file).isDirectory()) { + newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; + } + break; + } + + if (options.verbose) { + log(file + ' -> ' + newPerms.toString(8)); + } + + if (perms != newPerms) { + if (!options.verbose && options.changes) { + log(file + ' -> ' + newPerms.toString(8)); + } + fs.chmodSync(file, newPerms); + } + } + else { + error('Invalid symbolic mode change: ' + symbolicMode); + } + }); + } + else { + // they gave us a full number + newPerms = type + parseInt(mode, 8); + + // POSIX rules are that setuid and setgid can only be added using numeric form, but not cleared. + if (fs.statSync(file).isDirectory()) { + newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; + } + + fs.chmodSync(file, newPerms); + } + }); +} +exports.chmod = wrap('chmod', _chmod); + + +//@ +//@ ## Configuration +//@ + + + +exports.config = config; + +//@ +//@ ### config.silent +//@ Example: +//@ +//@ ```javascript +//@ var silentState = config.silent; // save old silent state +//@ config.silent = true; +//@ /* ... */ +//@ config.silent = silentState; // restore old silent state +//@ ``` +//@ +//@ Suppresses all command output if `true`, except for `echo()` calls. +//@ Default is `false`. + +//@ +//@ ### config.fatal +//@ Example: +//@ +//@ ```javascript +//@ config.fatal = true; +//@ cp('this_file_does_not_exist', '/dev/null'); // dies here +//@ /* more commands... */ +//@ ``` +//@ +//@ If `true` the script will die on errors. Default is `false`. + + + + +//@ +//@ ## Non-Unix commands +//@ + + + + + + +//@ +//@ ### tempdir() +//@ Searches and returns string containing a writeable, platform-dependent temporary directory. +//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). +exports.tempdir = wrap('tempdir', tempDir); + + +//@ +//@ ### error() +//@ Tests if error occurred in the last command. Returns `null` if no error occurred, +//@ otherwise returns string explaining the error +exports.error = function() { + return state.error; +}; + + + + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// +// Auxiliary functions (internal use only) +// + +function log() { + if (!config.silent) + console.log.apply(this, arguments); +} + +function deprecate(what, msg) { + console.log('*** ShellJS.'+what+': This function is deprecated.', msg); +} + +function write(msg) { + if (!config.silent) + process.stdout.write(msg); +} + +// Shows error message. Throws unless _continue or config.fatal are true +function error(msg, _continue) { + if (state.error === null) + state.error = ''; + state.error += state.currentCmd + ': ' + msg + '\n'; + + log(state.error); + + if (config.fatal) + process.exit(1); + + if (!_continue) + throw ''; +} + +// Returns {'alice': true, 'bob': false} when passed: +// parseOptions('-a', {'a':'alice', 'b':'bob'}); +function parseOptions(str, map) { + if (!map) + error('parseOptions() internal error: no map given'); + + // All options are false by default + var options = {}; + for (var letter in map) + options[map[letter]] = false; + + if (!str) + return options; // defaults + + if (typeof str !== 'string') + error('parseOptions() internal error: wrong str'); + + // e.g. match[1] = 'Rf' for str = '-Rf' + var match = str.match(/^\-(.+)/); + if (!match) + return options; + + // e.g. chars = ['R', 'f'] + var chars = match[1].split(''); + + chars.forEach(function(c) { + if (c in map) + options[map[c]] = true; + else + error('option not recognized: '+c); + }); + + return options; +} + +// Common wrapper for all Unix-like commands +function wrap(cmd, fn, options) { + return function() { + var retValue = null; + + state.currentCmd = cmd; + state.error = null; + + try { + var args = [].slice.call(arguments, 0); + + if (options && options.notUnix) { + retValue = fn.apply(this, args); + } else { + if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-') + args.unshift(''); // only add dummy option if '-option' not already present + retValue = fn.apply(this, args); + } + } catch (e) { + if (!state.error) { + // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... + console.log('shell.js: internal error'); + console.log(e.stack || e); + process.exit(1); + } + if (config.fatal) + throw e; + } + + state.currentCmd = 'shell.js'; + return retValue; + }; +} // wrap + +// Buffered file copy, synchronous +// (Using readFileSync() + writeFileSync() could easily cause a memory overflow +// with large files) +function copyFileSync(srcFile, destFile) { + if (!fs.existsSync(srcFile)) + error('copyFileSync: no such file or directory: ' + srcFile); + + var BUF_LENGTH = 64*1024, + buf = new Buffer(BUF_LENGTH), + bytesRead = BUF_LENGTH, + pos = 0, + fdr = null, + fdw = null; + + try { + fdr = fs.openSync(srcFile, 'r'); + } catch(e) { + error('copyFileSync: could not read src file ('+srcFile+')'); + } + + try { + fdw = fs.openSync(destFile, 'w'); + } catch(e) { + error('copyFileSync: could not write to dest file (code='+e.code+'):'+destFile); + } + + while (bytesRead === BUF_LENGTH) { + bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos); + fs.writeSync(fdw, buf, 0, bytesRead); + pos += bytesRead; + } + + fs.closeSync(fdr); + fs.closeSync(fdw); +} + +// Recursively copies 'sourceDir' into 'destDir' +// Adapted from https://github.com/ryanmcgrath/wrench-js +// +// Copyright (c) 2010 Ryan McGrath +// Copyright (c) 2012 Artur Adib +// +// Licensed under the MIT License +// http://www.opensource.org/licenses/mit-license.php +function cpdirSyncRecursive(sourceDir, destDir, opts) { + if (!opts) opts = {}; + + /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ + var checkDir = fs.statSync(sourceDir); + try { + fs.mkdirSync(destDir, checkDir.mode); + } catch (e) { + //if the directory already exists, that's okay + if (e.code !== 'EEXIST') throw e; + } + + var files = fs.readdirSync(sourceDir); + + for(var i = 0; i < files.length; i++) { + var currFile = fs.lstatSync(sourceDir + "/" + files[i]); + + if (currFile.isDirectory()) { + /* recursion this thing right on back. */ + cpdirSyncRecursive(sourceDir + "/" + files[i], destDir + "/" + files[i], opts); + } else if (currFile.isSymbolicLink()) { + var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]); + fs.symlinkSync(symlinkFull, destDir + "/" + files[i]); + } else { + /* At this point, we've hit a file actually worth copying... so copy it on over. */ + if (fs.existsSync(destDir + "/" + files[i]) && !opts.force) { + log('skipping existing file: ' + files[i]); + } else { + copyFileSync(sourceDir + "/" + files[i], destDir + "/" + files[i]); + } + } + + } // for files +} // cpdirSyncRecursive + +// Recursively removes 'dir' +// Adapted from https://github.com/ryanmcgrath/wrench-js +// +// Copyright (c) 2010 Ryan McGrath +// Copyright (c) 2012 Artur Adib +// +// Licensed under the MIT License +// http://www.opensource.org/licenses/mit-license.php +function rmdirSyncRecursive(dir, force) { + var files; + + files = fs.readdirSync(dir); + + // Loop through and delete everything in the sub-tree after checking it + for(var i = 0; i < files.length; i++) { + var file = dir + "/" + files[i], + currFile = fs.lstatSync(file); + + if(currFile.isDirectory()) { // Recursive function back to the beginning + rmdirSyncRecursive(file, force); + } + + else if(currFile.isSymbolicLink()) { // Unlink symlinks + if (force || isWriteable(file)) { + try { + _unlinkSync(file); + } catch (e) { + error('could not remove file (code '+e.code+'): ' + file, true); + } + } + } + + else // Assume it's a file - perhaps a try/catch belongs here? + if (force || isWriteable(file)) { + try { + _unlinkSync(file); + } catch (e) { + error('could not remove file (code '+e.code+'): ' + file, true); + } + } + } + + // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. + // Huzzah for the shopkeep. + + var result; + try { + result = fs.rmdirSync(dir); + } catch(e) { + error('could not remove directory (code '+e.code+'): ' + dir, true); + } + + return result; +} // rmdirSyncRecursive + +// Recursively creates 'dir' +function mkdirSyncRecursive(dir) { + var baseDir = path.dirname(dir); + + // Base dir exists, no recursion necessary + if (fs.existsSync(baseDir)) { + fs.mkdirSync(dir, parseInt('0777', 8)); + return; + } + + // Base dir does not exist, go recursive + mkdirSyncRecursive(baseDir); + + // Base dir created, can create dir + fs.mkdirSync(dir, parseInt('0777', 8)); +} + +// e.g. 'shelljs_a5f185d0443ca...' +function randomFileName() { + function randomHash(count) { + if (count === 1) + return parseInt(16*Math.random(), 10).toString(16); + else { + var hash = ''; + for (var i=0; i<count; i++) + hash += randomHash(1); + return hash; + } + } + + return 'shelljs_'+randomHash(20); +} + +// Returns false if 'dir' is not a writeable directory, 'dir' otherwise +function writeableDir(dir) { + if (!dir || !fs.existsSync(dir)) + return false; + + if (!fs.statSync(dir).isDirectory()) + return false; + + var testFile = dir+'/'+randomFileName(); + try { + fs.writeFileSync(testFile, ' '); + _unlinkSync(testFile); + return dir; + } catch (e) { + return false; + } +} + +// Cross-platform method for getting an available temporary directory. +// Follows the algorithm of Python's tempfile.tempdir +// http://docs.python.org/library/tempfile.html#tempfile.tempdir +function tempDir() { + if (state.tempDir) + return state.tempDir; // from cache + + state.tempDir = writeableDir(process.env['TMPDIR']) || + writeableDir(process.env['TEMP']) || + writeableDir(process.env['TMP']) || + writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS + writeableDir('C:\\TEMP') || // Windows + writeableDir('C:\\TMP') || // Windows + writeableDir('\\TEMP') || // Windows + writeableDir('\\TMP') || // Windows + writeableDir('/tmp') || + writeableDir('/var/tmp') || + writeableDir('/usr/tmp') || + writeableDir('.'); // last resort + + return state.tempDir; +} + +// Wrapper around exec() to enable echoing output to console in real time +function execAsync(cmd, opts, callback) { + var output = ''; + + var options = extend({ + silent: config.silent + }, opts); + + var c = child.exec(cmd, {env: process.env, maxBuffer: 20*1024*1024}, function(err) { + if (callback) + callback(err ? err.code : 0, output); + }); + + c.stdout.on('data', function(data) { + output += data; + if (!options.silent) + process.stdout.write(data); + }); + + c.stderr.on('data', function(data) { + output += data; + if (!options.silent) + process.stdout.write(data); + }); + + return c; +} + +// Hack to run child_process.exec() synchronously (sync avoids callback hell) +// Uses a custom wait loop that checks for a flag file, created when the child process is done. +// (Can't do a wait loop that checks for internal Node variables/messages as +// Node is single-threaded; callbacks and other internal state changes are done in the +// event loop). +function execSync(cmd, opts) { + var stdoutFile = path.resolve(tempDir()+'/'+randomFileName()), + codeFile = path.resolve(tempDir()+'/'+randomFileName()), + scriptFile = path.resolve(tempDir()+'/'+randomFileName()), + sleepFile = path.resolve(tempDir()+'/'+randomFileName()); + + var options = extend({ + silent: config.silent + }, opts); + + var previousStdoutContent = ''; + // Echoes stdout changes from running process, if not silent + function updateStdout() { + if (options.silent || !fs.existsSync(stdoutFile)) + return; + + var stdoutContent = fs.readFileSync(stdoutFile, 'utf8'); + // No changes since last time? + if (stdoutContent.length <= previousStdoutContent.length) + return; + + process.stdout.write(stdoutContent.substr(previousStdoutContent.length)); + previousStdoutContent = stdoutContent; + } + + function escape(str) { + return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0"); + } + + cmd += ' > '+stdoutFile+' 2>&1'; // works on both win/unix + + var script = + "var child = require('child_process')," + + " fs = require('fs');" + + "child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {" + + " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');" + + "});"; + + if (fs.existsSync(scriptFile)) _unlinkSync(scriptFile); + if (fs.existsSync(stdoutFile)) _unlinkSync(stdoutFile); + if (fs.existsSync(codeFile)) _unlinkSync(codeFile); + + fs.writeFileSync(scriptFile, script); + child.exec('"'+process.execPath+'" '+scriptFile, { + env: process.env, + cwd: exports.pwd(), + maxBuffer: 20*1024*1024 + }); + + // The wait loop + // sleepFile is used as a dummy I/O op to mitigate unnecessary CPU usage + // (tried many I/O sync ops, writeFileSync() seems to be only one that is effective in reducing + // CPU usage, though apparently not so much on Windows) + while (!fs.existsSync(codeFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); } + while (!fs.existsSync(stdoutFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); } + + // At this point codeFile exists, but it's not necessarily flushed yet. + // Keep reading it until it is. + var code = parseInt('', 10); + while (isNaN(code)) { + code = parseInt(fs.readFileSync(codeFile, 'utf8'), 10); + } + + var stdout = fs.readFileSync(stdoutFile, 'utf8'); + + // No biggie if we can't erase the files now -- they're in a temp dir anyway + try { _unlinkSync(scriptFile); } catch(e) {} + try { _unlinkSync(stdoutFile); } catch(e) {} + try { _unlinkSync(codeFile); } catch(e) {} + try { _unlinkSync(sleepFile); } catch(e) {} + + // True if successful, false if not + var obj = { + code: code, + output: stdout + }; + return obj; +} // execSync() + +// Expands wildcards with matching file names. For a given array of file names 'list', returns +// another array containing all file names as per ls(list[i]). +// For example: +// expand(['file*.js']) = ['file1.js', 'file2.js', ...] +// (if the files 'file1.js', 'file2.js', etc, exist in the current dir) +function expand(list) { + var expanded = []; + list.forEach(function(listEl) { + // Wildcard present? + if (listEl.search(/\*/) > -1) { + _ls('', listEl).forEach(function(file) { + expanded.push(file); + }); + } else { + expanded.push(listEl); + } + }); + return expanded; +} + +// Cross-platform method for splitting environment PATH variables +function splitPath(p) { + if (!p) + return []; + + if (platform === 'win') + return p.split(';'); + else + return p.split(':'); +} + +// extend(target_obj, source_obj1 [, source_obj2 ...]) +// Shallow extend, e.g.: +// extend({A:1}, {b:2}, {c:3}) returns {A:1, b:2, c:3} +function extend(target) { + var sources = [].slice.call(arguments, 1); + sources.forEach(function(source) { + for (var key in source) + target[key] = source[key]; + }); + + return target; +} + +// Normalizes _unlinkSync() across platforms to match Unix behavior, i.e. +// file can be unlinked even if it's read-only, see joyent/node#3006 +function _unlinkSync(file) { + try { + fs.unlinkSync(file); + } catch(e) { + // Try to override file permission + if (e.code === 'EPERM') { + fs.chmodSync(file, '0666'); + fs.unlinkSync(file); + } else { + throw e; + } + } +} + +// Hack to determine if file has write permissions for current user +// Avoids having to check user, group, etc, but it's probably slow +function isWriteable(file) { + var writePermission = true; + try { + var __fd = fs.openSync(file, 'a'); + fs.closeSync(__fd); + } catch(e) { + writePermission = false; + } + + return writePermission; +} diff --git a/StoneIsland/platforms/ios/cordova/run b/StoneIsland/platforms/ios/cordova/run new file mode 100755 index 00000000..d2c376d5 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/run @@ -0,0 +1,36 @@ +#!/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, + run = require('./lib/run'); + +// Handle help flag +if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(args[2]) > -1) { + run.help(); +} else { + run.run(args).done(function() { + console.log('** RUN SUCCEEDED **'); + }, function (err) { + var errorMessage = (err && err.stack) ? err.stack : err; + console.error(errorMessage); + process.exit(2); + }); +}
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/cordova/run.bat b/StoneIsland/platforms/ios/cordova/run.bat new file mode 100755 index 00000000..0d10321a --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/run.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="%~dp0run" +IF EXIST %script_path% ( + node %script_path% %* +) ELSE ( + ECHO. + ECHO ERROR: Could not find 'run' script in 'cordova' folder, aborting...>&2 + EXIT /B 1 +) diff --git a/StoneIsland/platforms/ios/cordova/version b/StoneIsland/platforms/ios/cordova/version new file mode 100755 index 00000000..075913e5 --- /dev/null +++ b/StoneIsland/platforms/ios/cordova/version @@ -0,0 +1,30 @@ +#!/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. +*/ + +var VERSION="3.8.0" + +console.log(VERSION); diff --git a/StoneIsland/platforms/ios/cordova/version.bat b/StoneIsland/platforms/ios/cordova/version.bat new file mode 100755 index 00000000..84c86b43 --- /dev/null +++ b/StoneIsland/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/StoneIsland/platforms/ios/platform_www/cordova-js-src/exec.js b/StoneIsland/platforms/ios/platform_www/cordova-js-src/exec.js new file mode 100644 index 00000000..32a3f8b5 --- /dev/null +++ b/StoneIsland/platforms/ios/platform_www/cordova-js-src/exec.js @@ -0,0 +1,323 @@ +/* + * + * 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. + * +*/ + +/** + * Creates a gap bridge iframe used to notify the native code about queued + * commands. + */ +var cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + base64 = require('cordova/base64'), + // XHR mode does not work on iOS 4.2. + // XHR mode's main advantage is working around a bug in -webkit-scroll, which + // doesn't exist only on iOS 5.x devices. + // IFRAME_NAV is the fastest. + // IFRAME_HASH could be made to enable synchronous bridge calls if we wanted this feature. + jsToNativeModes = { + IFRAME_NAV: 0, // Default. Uses a new iframe for each poke. + // XHR bridge appears to be flaky sometimes: CB-3900, CB-3359, CB-5457, CB-4970, CB-4998, CB-5134 + XHR_NO_PAYLOAD: 1, // About the same speed as IFRAME_NAV. Performance not about the same as IFRAME_NAV, but more variable. + XHR_WITH_PAYLOAD: 2, // Flakey, and not as performant + XHR_OPTIONAL_PAYLOAD: 3, // Flakey, and not as performant + IFRAME_HASH_NO_PAYLOAD: 4, // Not fully baked. A bit faster than IFRAME_NAV, but risks jank since poke happens synchronously. + IFRAME_HASH_WITH_PAYLOAD: 5, // Slower than no payload. Maybe since it has to be URI encoded / decoded. + WK_WEBVIEW_BINDING: 6 // Only way that works for WKWebView :) + }, + bridgeMode, + execIframe, + execHashIframe, + hashToggle = 1, + execXhr, + requestCount = 0, + vcHeaderValue = null, + commandQueue = [], // Contains pending JS->Native messages. + isInContextOfEvalJs = 0, + failSafeTimerId = 0; + +function shouldBundleCommandJson() { + if (bridgeMode === jsToNativeModes.XHR_WITH_PAYLOAD) { + return true; + } + if (bridgeMode === jsToNativeModes.XHR_OPTIONAL_PAYLOAD) { + var payloadLength = 0; + for (var i = 0; i < commandQueue.length; ++i) { + payloadLength += commandQueue[i].length; + } + // The value here was determined using the benchmark within CordovaLibApp on an iPad 3. + return payloadLength < 4500; + } + return false; +} + +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() { + if (bridgeMode === undefined) { + bridgeMode = jsToNativeModes.IFRAME_NAV; + } + + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) { + bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING; + } + + var successCallback, failCallback, service, action, actionArgs, splitCommand; + 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 { + // FORMAT TWO, REMOVED + try { + splitCommand = arguments[0].split("."); + action = splitCommand.pop(); + service = splitCommand.join("."); + actionArgs = Array.prototype.splice.call(arguments, 1); + + console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + + "cordova.exec(null, null, \"" + service + "\", \"" + action + "\"," + JSON.stringify(actionArgs) + ");" + ); + return; + } catch (e) {} + } + + // 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 (bridgeMode === jsToNativeModes.WK_WEBVIEW_BINDING) { + window.webkit.messageHandlers.cordova.postMessage(command); + } else { + // 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(); + } + } +} + +function pokeNative() { + switch (bridgeMode) { + case jsToNativeModes.XHR_NO_PAYLOAD: + case jsToNativeModes.XHR_WITH_PAYLOAD: + case jsToNativeModes.XHR_OPTIONAL_PAYLOAD: + pokeNativeViaXhr(); + break; + default: // iframe-based. + pokeNativeViaIframe(); + } +} + +function pokeNativeViaXhr() { + // This prevents sending an XHR when there is already one being sent. + // This should happen only in rare circumstances (refer to unit tests). + if (execXhr && execXhr.readyState != 4) { + execXhr = null; + } + // Re-using the XHR improves exec() performance by about 10%. + execXhr = execXhr || new XMLHttpRequest(); + // Changing this to a GET will make the XHR reach the URIProtocol on 4.2. + // For some reason it still doesn't work though... + // Add a timestamp to the query param to prevent caching. + execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true); + if (!vcHeaderValue) { + vcHeaderValue = /.*\((.*)\)$/.exec(navigator.userAgent)[1]; + } + execXhr.setRequestHeader('vc', vcHeaderValue); + execXhr.setRequestHeader('rc', ++requestCount); + if (shouldBundleCommandJson()) { + execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages()); + } + execXhr.send(null); +} + +function pokeNativeViaIframe() { + // CB-5488 - Don't attempt to create iframe before document.body is available. + if (!document.body) { + setTimeout(pokeNativeViaIframe); + return; + } + if (bridgeMode === jsToNativeModes.IFRAME_HASH_NO_PAYLOAD || bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + // TODO: This bridge mode doesn't properly support being removed from the DOM (CB-7735) + if (!execHashIframe) { + execHashIframe = document.createElement('iframe'); + execHashIframe.style.display = 'none'; + document.body.appendChild(execHashIframe); + // Hash changes don't work on about:blank, so switch it to file:///. + execHashIframe.contentWindow.history.replaceState(null, null, 'file:///#'); + } + // The delegate method is called only when the hash changes, so toggle it back and forth. + hashToggle = hashToggle ^ 3; + var hashValue = '%0' + hashToggle; + if (bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + hashValue += iOSExec.nativeFetchMessages(); + } + execHashIframe.contentWindow.location.hash = hashValue; + } else { + // 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) { + pokeNative(); + } + }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire). + } +} + +iOSExec.jsToNativeModes = jsToNativeModes; + +iOSExec.setJsToNativeBridgeMode = function(mode) { + // Remove the iFrame since it may be no longer required, and its existence + // can trigger browser bugs. + // https://issues.apache.org/jira/browse/CB-593 + if (execIframe) { + if (execIframe.parentNode) { + execIframe.parentNode.removeChild(execIframe); + } + execIframe = null; + } + bridgeMode = mode; +}; + +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) { + return iOSExec.nativeEvalAndFetch(function() { + var success = status === 0 || status === 1; + var args = convertMessageToArgsNativeToJs(message); + cordova.callbackFromNative(callbackId, success, status, args, keepCallback); + }); +}; + +iOSExec.nativeEvalAndFetch = function(func) { + // This shouldn't be nested, but better to be safe. + isInContextOfEvalJs++; + try { + func(); + return iOSExec.nativeFetchMessages(); + } finally { + isInContextOfEvalJs--; + } +}; + +module.exports = iOSExec; diff --git a/StoneIsland/platforms/ios/platform_www/cordova-js-src/platform.js b/StoneIsland/platforms/ios/platform_www/cordova-js-src/platform.js new file mode 100644 index 00000000..36529ba5 --- /dev/null +++ b/StoneIsland/platforms/ios/platform_www/cordova-js-src/platform.js @@ -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. + * +*/ + +module.exports = { + id: 'ios', + bootstrap: function() { + require('cordova/channel').onNativeReady.fire(); + } +}; + diff --git a/StoneIsland/platforms/ios/platform_www/cordova.js b/StoneIsland/platforms/ios/platform_www/cordova.js new file mode 100644 index 00000000..4f781077 --- /dev/null +++ b/StoneIsland/platforms/ios/platform_www/cordova.js @@ -0,0 +1,1810 @@ +// Platform: ios +// fc4db9145934bd0053161cbf9ffc0caf83b770c6 +/* + 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 = '3.8.0'; +// file: src/scripts/require.js + +/*jshint -W079 */ +/*jshint -W020 */ + +var require, + define; + +(function () { + var modules = {}, + // Stack of moduleIds currently being built. + requireStack = [], + // Map of module ID -> index into requireStack of modules currently being built. + inProgressModules = {}, + SEPARATOR = "."; + + + + function build(module) { + var factory = module.factory, + 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 (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) { + + +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 = {}, + 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); + 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 exec = require('cordova/exec'); +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 (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex]; +} + +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), + cUpper = c.toUpperCase(), + 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 = typeof atob != 'undefined' ? atob(str) : new Buffer(str,'base64').toString('binary'); + 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) { + exports.replaceHookForTesting(obj, key); + 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; +exports.replaceHookForTesting = function() {}; + +}); + +// file: src/common/channel.js +define("cordova/channel", function(require, exports, module) { + +var utils = require('cordova/utils'), + 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; +}, + 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, + i = len, + 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 forceFunction(f) { + if (typeof f != 'function') throw "Function required as first argument!"; +} + +/** + * 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(f, c) { + // need a function to call + forceFunction(f); + if (this.state == 2) { + f.apply(c || this, this.fireArgs); + return; + } + + var func = f, + guid = f.observer_guid; + if (typeof c == "object") { func = utils.close(c, f); } + + if (!guid) { + // first time any channel has seen this subscriber + guid = '' + nextGuid++; + } + func.observer_guid = guid; + f.observer_guid = guid; + + // Don't add the same handler more than once. + if (!this.handlers[guid]) { + this.handlers[guid] = func; + this.numHandlers++; + if (this.numHandlers == 1) { + this.onHasSubscribersChange && this.onHasSubscribersChange(); + } + } +}; + +/** + * Unsubscribes the function with the given guid from the channel. + */ +Channel.prototype.unsubscribe = function(f) { + // need a function to unsubscribe + forceFunction(f); + + var guid = f.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 fail = false, + 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: src/ios/exec.js +define("cordova/exec", function(require, exports, module) { + +/** + * Creates a gap bridge iframe used to notify the native code about queued + * commands. + */ +var cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + base64 = require('cordova/base64'), + // XHR mode does not work on iOS 4.2. + // XHR mode's main advantage is working around a bug in -webkit-scroll, which + // doesn't exist only on iOS 5.x devices. + // IFRAME_NAV is the fastest. + // IFRAME_HASH could be made to enable synchronous bridge calls if we wanted this feature. + jsToNativeModes = { + IFRAME_NAV: 0, // Default. Uses a new iframe for each poke. + // XHR bridge appears to be flaky sometimes: CB-3900, CB-3359, CB-5457, CB-4970, CB-4998, CB-5134 + XHR_NO_PAYLOAD: 1, // About the same speed as IFRAME_NAV. Performance not about the same as IFRAME_NAV, but more variable. + XHR_WITH_PAYLOAD: 2, // Flakey, and not as performant + XHR_OPTIONAL_PAYLOAD: 3, // Flakey, and not as performant + IFRAME_HASH_NO_PAYLOAD: 4, // Not fully baked. A bit faster than IFRAME_NAV, but risks jank since poke happens synchronously. + IFRAME_HASH_WITH_PAYLOAD: 5, // Slower than no payload. Maybe since it has to be URI encoded / decoded. + WK_WEBVIEW_BINDING: 6 // Only way that works for WKWebView :) + }, + bridgeMode, + execIframe, + execHashIframe, + hashToggle = 1, + execXhr, + requestCount = 0, + vcHeaderValue = null, + commandQueue = [], // Contains pending JS->Native messages. + isInContextOfEvalJs = 0, + failSafeTimerId = 0; + +function shouldBundleCommandJson() { + if (bridgeMode === jsToNativeModes.XHR_WITH_PAYLOAD) { + return true; + } + if (bridgeMode === jsToNativeModes.XHR_OPTIONAL_PAYLOAD) { + var payloadLength = 0; + for (var i = 0; i < commandQueue.length; ++i) { + payloadLength += commandQueue[i].length; + } + // The value here was determined using the benchmark within CordovaLibApp on an iPad 3. + return payloadLength < 4500; + } + return false; +} + +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() { + if (bridgeMode === undefined) { + bridgeMode = jsToNativeModes.IFRAME_NAV; + } + + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) { + bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING; + } + + var successCallback, failCallback, service, action, actionArgs, splitCommand; + 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 { + // FORMAT TWO, REMOVED + try { + splitCommand = arguments[0].split("."); + action = splitCommand.pop(); + service = splitCommand.join("."); + actionArgs = Array.prototype.splice.call(arguments, 1); + + console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + + "cordova.exec(null, null, \"" + service + "\", \"" + action + "\"," + JSON.stringify(actionArgs) + ");" + ); + return; + } catch (e) {} + } + + // 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 (bridgeMode === jsToNativeModes.WK_WEBVIEW_BINDING) { + window.webkit.messageHandlers.cordova.postMessage(command); + } else { + // 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(); + } + } +} + +function pokeNative() { + switch (bridgeMode) { + case jsToNativeModes.XHR_NO_PAYLOAD: + case jsToNativeModes.XHR_WITH_PAYLOAD: + case jsToNativeModes.XHR_OPTIONAL_PAYLOAD: + pokeNativeViaXhr(); + break; + default: // iframe-based. + pokeNativeViaIframe(); + } +} + +function pokeNativeViaXhr() { + // This prevents sending an XHR when there is already one being sent. + // This should happen only in rare circumstances (refer to unit tests). + if (execXhr && execXhr.readyState != 4) { + execXhr = null; + } + // Re-using the XHR improves exec() performance by about 10%. + execXhr = execXhr || new XMLHttpRequest(); + // Changing this to a GET will make the XHR reach the URIProtocol on 4.2. + // For some reason it still doesn't work though... + // Add a timestamp to the query param to prevent caching. + execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true); + if (!vcHeaderValue) { + vcHeaderValue = /.*\((.*)\)$/.exec(navigator.userAgent)[1]; + } + execXhr.setRequestHeader('vc', vcHeaderValue); + execXhr.setRequestHeader('rc', ++requestCount); + if (shouldBundleCommandJson()) { + execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages()); + } + execXhr.send(null); +} + +function pokeNativeViaIframe() { + // CB-5488 - Don't attempt to create iframe before document.body is available. + if (!document.body) { + setTimeout(pokeNativeViaIframe); + return; + } + if (bridgeMode === jsToNativeModes.IFRAME_HASH_NO_PAYLOAD || bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + // TODO: This bridge mode doesn't properly support being removed from the DOM (CB-7735) + if (!execHashIframe) { + execHashIframe = document.createElement('iframe'); + execHashIframe.style.display = 'none'; + document.body.appendChild(execHashIframe); + // Hash changes don't work on about:blank, so switch it to file:///. + execHashIframe.contentWindow.history.replaceState(null, null, 'file:///#'); + } + // The delegate method is called only when the hash changes, so toggle it back and forth. + hashToggle = hashToggle ^ 3; + var hashValue = '%0' + hashToggle; + if (bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + hashValue += iOSExec.nativeFetchMessages(); + } + execHashIframe.contentWindow.location.hash = hashValue; + } else { + // 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) { + pokeNative(); + } + }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire). + } +} + +iOSExec.jsToNativeModes = jsToNativeModes; + +iOSExec.setJsToNativeBridgeMode = function(mode) { + // Remove the iFrame since it may be no longer required, and its existence + // can trigger browser bugs. + // https://issues.apache.org/jira/browse/CB-593 + if (execIframe) { + if (execIframe.parentNode) { + execIframe.parentNode.removeChild(execIframe); + } + execIframe = null; + } + bridgeMode = mode; +}; + +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) { + return iOSExec.nativeEvalAndFetch(function() { + var success = status === 0 || status === 1; + var args = convertMessageToArgsNativeToJs(message); + cordova.callbackFromNative(callbackId, success, status, args, keepCallback); + }); +}; + +iOSExec.nativeEvalAndFetch = function(func) { + // This shouldn't be nested, but better to be safe. + isInContextOfEvalJs++; + try { + func(); + return iOSExec.nativeFetchMessages(); + } finally { + isInContextOfEvalJs--; + } +}; + +module.exports = iOSExec; + +}); + +// 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.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/init_b.js +define("cordova/init_b", function(require, exports, module) { + +var channel = require('cordova/channel'); +var cordova = require('cordova'); +var platform = require('cordova/platform'); +var utils = require('cordova/utils'); + +var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady]; + +// setting exec +cordova.exec = require('cordova/exec'); + +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.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(); +} + +// Call the platform-specific initialization. +platform.bootstrap && platform.bootstrap(); + +/** + * Create all cordova objects once native side is ready. + */ +channel.join(function() { + + 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'), + moduleMap = define.moduleMap, + symbolList, + 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; + } + var parts = symbolPath.split('.'); + var cur = context; + for (var i = 0, part; part = parts[i]; ++i) { + cur = cur[part] = cur[part] || {}; + } + return cur; +} + +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: src/ios/platform.js +define("cordova/platform", function(require, exports, module) { + +module.exports = { + id: 'ios', + bootstrap: function() { + require('cordova/channel').onNativeReady.fire(); + } +}; + + +}); + +// file: src/common/pluginloader.js +define("cordova/pluginloader", function(require, exports, module) { + +var modulemapper = require('cordova/modulemapper'); +var urlutil = require('cordova/urlutil'); + +// 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 = function(a) { + return utils.typeName(a) == 'Array'; +}; + +/** + * Returns an indication of whether the argument is a Date or not + */ +utils.isDate = function(d) { + return utils.typeName(d) == '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){ + if(!(i in retVal) || retVal[i] != obj[i]) { + retVal[i] = utils.clone(obj[i]); + } + } + return retVal; +}; + +/** + * Returns a wrapped version of the function + */ +utils.close = function(context, func, params) { + if (typeof params == 'undefined') { + return function() { + return func.apply(context, arguments); + }; + } else { + return function() { + return func.apply(context, params); + }; + } +}; + +/** + * 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); + } +}; + + +//------------------------------------------------------------------------------ +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; +} + + +}); + +window.cordova = require('cordova'); +// file: src/scripts/bootstrap.js + +require('cordova/init'); + +})();
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/www/cordova-js-src/exec.js b/StoneIsland/platforms/ios/www/cordova-js-src/exec.js new file mode 100644 index 00000000..32a3f8b5 --- /dev/null +++ b/StoneIsland/platforms/ios/www/cordova-js-src/exec.js @@ -0,0 +1,323 @@ +/* + * + * 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. + * +*/ + +/** + * Creates a gap bridge iframe used to notify the native code about queued + * commands. + */ +var cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + base64 = require('cordova/base64'), + // XHR mode does not work on iOS 4.2. + // XHR mode's main advantage is working around a bug in -webkit-scroll, which + // doesn't exist only on iOS 5.x devices. + // IFRAME_NAV is the fastest. + // IFRAME_HASH could be made to enable synchronous bridge calls if we wanted this feature. + jsToNativeModes = { + IFRAME_NAV: 0, // Default. Uses a new iframe for each poke. + // XHR bridge appears to be flaky sometimes: CB-3900, CB-3359, CB-5457, CB-4970, CB-4998, CB-5134 + XHR_NO_PAYLOAD: 1, // About the same speed as IFRAME_NAV. Performance not about the same as IFRAME_NAV, but more variable. + XHR_WITH_PAYLOAD: 2, // Flakey, and not as performant + XHR_OPTIONAL_PAYLOAD: 3, // Flakey, and not as performant + IFRAME_HASH_NO_PAYLOAD: 4, // Not fully baked. A bit faster than IFRAME_NAV, but risks jank since poke happens synchronously. + IFRAME_HASH_WITH_PAYLOAD: 5, // Slower than no payload. Maybe since it has to be URI encoded / decoded. + WK_WEBVIEW_BINDING: 6 // Only way that works for WKWebView :) + }, + bridgeMode, + execIframe, + execHashIframe, + hashToggle = 1, + execXhr, + requestCount = 0, + vcHeaderValue = null, + commandQueue = [], // Contains pending JS->Native messages. + isInContextOfEvalJs = 0, + failSafeTimerId = 0; + +function shouldBundleCommandJson() { + if (bridgeMode === jsToNativeModes.XHR_WITH_PAYLOAD) { + return true; + } + if (bridgeMode === jsToNativeModes.XHR_OPTIONAL_PAYLOAD) { + var payloadLength = 0; + for (var i = 0; i < commandQueue.length; ++i) { + payloadLength += commandQueue[i].length; + } + // The value here was determined using the benchmark within CordovaLibApp on an iPad 3. + return payloadLength < 4500; + } + return false; +} + +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() { + if (bridgeMode === undefined) { + bridgeMode = jsToNativeModes.IFRAME_NAV; + } + + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) { + bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING; + } + + var successCallback, failCallback, service, action, actionArgs, splitCommand; + 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 { + // FORMAT TWO, REMOVED + try { + splitCommand = arguments[0].split("."); + action = splitCommand.pop(); + service = splitCommand.join("."); + actionArgs = Array.prototype.splice.call(arguments, 1); + + console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + + "cordova.exec(null, null, \"" + service + "\", \"" + action + "\"," + JSON.stringify(actionArgs) + ");" + ); + return; + } catch (e) {} + } + + // 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 (bridgeMode === jsToNativeModes.WK_WEBVIEW_BINDING) { + window.webkit.messageHandlers.cordova.postMessage(command); + } else { + // 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(); + } + } +} + +function pokeNative() { + switch (bridgeMode) { + case jsToNativeModes.XHR_NO_PAYLOAD: + case jsToNativeModes.XHR_WITH_PAYLOAD: + case jsToNativeModes.XHR_OPTIONAL_PAYLOAD: + pokeNativeViaXhr(); + break; + default: // iframe-based. + pokeNativeViaIframe(); + } +} + +function pokeNativeViaXhr() { + // This prevents sending an XHR when there is already one being sent. + // This should happen only in rare circumstances (refer to unit tests). + if (execXhr && execXhr.readyState != 4) { + execXhr = null; + } + // Re-using the XHR improves exec() performance by about 10%. + execXhr = execXhr || new XMLHttpRequest(); + // Changing this to a GET will make the XHR reach the URIProtocol on 4.2. + // For some reason it still doesn't work though... + // Add a timestamp to the query param to prevent caching. + execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true); + if (!vcHeaderValue) { + vcHeaderValue = /.*\((.*)\)$/.exec(navigator.userAgent)[1]; + } + execXhr.setRequestHeader('vc', vcHeaderValue); + execXhr.setRequestHeader('rc', ++requestCount); + if (shouldBundleCommandJson()) { + execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages()); + } + execXhr.send(null); +} + +function pokeNativeViaIframe() { + // CB-5488 - Don't attempt to create iframe before document.body is available. + if (!document.body) { + setTimeout(pokeNativeViaIframe); + return; + } + if (bridgeMode === jsToNativeModes.IFRAME_HASH_NO_PAYLOAD || bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + // TODO: This bridge mode doesn't properly support being removed from the DOM (CB-7735) + if (!execHashIframe) { + execHashIframe = document.createElement('iframe'); + execHashIframe.style.display = 'none'; + document.body.appendChild(execHashIframe); + // Hash changes don't work on about:blank, so switch it to file:///. + execHashIframe.contentWindow.history.replaceState(null, null, 'file:///#'); + } + // The delegate method is called only when the hash changes, so toggle it back and forth. + hashToggle = hashToggle ^ 3; + var hashValue = '%0' + hashToggle; + if (bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + hashValue += iOSExec.nativeFetchMessages(); + } + execHashIframe.contentWindow.location.hash = hashValue; + } else { + // 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) { + pokeNative(); + } + }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire). + } +} + +iOSExec.jsToNativeModes = jsToNativeModes; + +iOSExec.setJsToNativeBridgeMode = function(mode) { + // Remove the iFrame since it may be no longer required, and its existence + // can trigger browser bugs. + // https://issues.apache.org/jira/browse/CB-593 + if (execIframe) { + if (execIframe.parentNode) { + execIframe.parentNode.removeChild(execIframe); + } + execIframe = null; + } + bridgeMode = mode; +}; + +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) { + return iOSExec.nativeEvalAndFetch(function() { + var success = status === 0 || status === 1; + var args = convertMessageToArgsNativeToJs(message); + cordova.callbackFromNative(callbackId, success, status, args, keepCallback); + }); +}; + +iOSExec.nativeEvalAndFetch = function(func) { + // This shouldn't be nested, but better to be safe. + isInContextOfEvalJs++; + try { + func(); + return iOSExec.nativeFetchMessages(); + } finally { + isInContextOfEvalJs--; + } +}; + +module.exports = iOSExec; diff --git a/StoneIsland/platforms/ios/www/cordova-js-src/platform.js b/StoneIsland/platforms/ios/www/cordova-js-src/platform.js new file mode 100644 index 00000000..36529ba5 --- /dev/null +++ b/StoneIsland/platforms/ios/www/cordova-js-src/platform.js @@ -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. + * +*/ + +module.exports = { + id: 'ios', + bootstrap: function() { + require('cordova/channel').onNativeReady.fire(); + } +}; + diff --git a/StoneIsland/platforms/ios/www/cordova.js b/StoneIsland/platforms/ios/www/cordova.js new file mode 100644 index 00000000..4f781077 --- /dev/null +++ b/StoneIsland/platforms/ios/www/cordova.js @@ -0,0 +1,1810 @@ +// Platform: ios +// fc4db9145934bd0053161cbf9ffc0caf83b770c6 +/* + 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 = '3.8.0'; +// file: src/scripts/require.js + +/*jshint -W079 */ +/*jshint -W020 */ + +var require, + define; + +(function () { + var modules = {}, + // Stack of moduleIds currently being built. + requireStack = [], + // Map of module ID -> index into requireStack of modules currently being built. + inProgressModules = {}, + SEPARATOR = "."; + + + + function build(module) { + var factory = module.factory, + 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 (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) { + + +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 = {}, + 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); + 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 exec = require('cordova/exec'); +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 (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex]; +} + +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), + cUpper = c.toUpperCase(), + 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 = typeof atob != 'undefined' ? atob(str) : new Buffer(str,'base64').toString('binary'); + 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) { + exports.replaceHookForTesting(obj, key); + 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; +exports.replaceHookForTesting = function() {}; + +}); + +// file: src/common/channel.js +define("cordova/channel", function(require, exports, module) { + +var utils = require('cordova/utils'), + 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; +}, + 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, + i = len, + 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 forceFunction(f) { + if (typeof f != 'function') throw "Function required as first argument!"; +} + +/** + * 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(f, c) { + // need a function to call + forceFunction(f); + if (this.state == 2) { + f.apply(c || this, this.fireArgs); + return; + } + + var func = f, + guid = f.observer_guid; + if (typeof c == "object") { func = utils.close(c, f); } + + if (!guid) { + // first time any channel has seen this subscriber + guid = '' + nextGuid++; + } + func.observer_guid = guid; + f.observer_guid = guid; + + // Don't add the same handler more than once. + if (!this.handlers[guid]) { + this.handlers[guid] = func; + this.numHandlers++; + if (this.numHandlers == 1) { + this.onHasSubscribersChange && this.onHasSubscribersChange(); + } + } +}; + +/** + * Unsubscribes the function with the given guid from the channel. + */ +Channel.prototype.unsubscribe = function(f) { + // need a function to unsubscribe + forceFunction(f); + + var guid = f.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 fail = false, + 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: src/ios/exec.js +define("cordova/exec", function(require, exports, module) { + +/** + * Creates a gap bridge iframe used to notify the native code about queued + * commands. + */ +var cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + base64 = require('cordova/base64'), + // XHR mode does not work on iOS 4.2. + // XHR mode's main advantage is working around a bug in -webkit-scroll, which + // doesn't exist only on iOS 5.x devices. + // IFRAME_NAV is the fastest. + // IFRAME_HASH could be made to enable synchronous bridge calls if we wanted this feature. + jsToNativeModes = { + IFRAME_NAV: 0, // Default. Uses a new iframe for each poke. + // XHR bridge appears to be flaky sometimes: CB-3900, CB-3359, CB-5457, CB-4970, CB-4998, CB-5134 + XHR_NO_PAYLOAD: 1, // About the same speed as IFRAME_NAV. Performance not about the same as IFRAME_NAV, but more variable. + XHR_WITH_PAYLOAD: 2, // Flakey, and not as performant + XHR_OPTIONAL_PAYLOAD: 3, // Flakey, and not as performant + IFRAME_HASH_NO_PAYLOAD: 4, // Not fully baked. A bit faster than IFRAME_NAV, but risks jank since poke happens synchronously. + IFRAME_HASH_WITH_PAYLOAD: 5, // Slower than no payload. Maybe since it has to be URI encoded / decoded. + WK_WEBVIEW_BINDING: 6 // Only way that works for WKWebView :) + }, + bridgeMode, + execIframe, + execHashIframe, + hashToggle = 1, + execXhr, + requestCount = 0, + vcHeaderValue = null, + commandQueue = [], // Contains pending JS->Native messages. + isInContextOfEvalJs = 0, + failSafeTimerId = 0; + +function shouldBundleCommandJson() { + if (bridgeMode === jsToNativeModes.XHR_WITH_PAYLOAD) { + return true; + } + if (bridgeMode === jsToNativeModes.XHR_OPTIONAL_PAYLOAD) { + var payloadLength = 0; + for (var i = 0; i < commandQueue.length; ++i) { + payloadLength += commandQueue[i].length; + } + // The value here was determined using the benchmark within CordovaLibApp on an iPad 3. + return payloadLength < 4500; + } + return false; +} + +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() { + if (bridgeMode === undefined) { + bridgeMode = jsToNativeModes.IFRAME_NAV; + } + + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) { + bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING; + } + + var successCallback, failCallback, service, action, actionArgs, splitCommand; + 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 { + // FORMAT TWO, REMOVED + try { + splitCommand = arguments[0].split("."); + action = splitCommand.pop(); + service = splitCommand.join("."); + actionArgs = Array.prototype.splice.call(arguments, 1); + + console.log('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + + "cordova.exec(null, null, \"" + service + "\", \"" + action + "\"," + JSON.stringify(actionArgs) + ");" + ); + return; + } catch (e) {} + } + + // 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 (bridgeMode === jsToNativeModes.WK_WEBVIEW_BINDING) { + window.webkit.messageHandlers.cordova.postMessage(command); + } else { + // 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(); + } + } +} + +function pokeNative() { + switch (bridgeMode) { + case jsToNativeModes.XHR_NO_PAYLOAD: + case jsToNativeModes.XHR_WITH_PAYLOAD: + case jsToNativeModes.XHR_OPTIONAL_PAYLOAD: + pokeNativeViaXhr(); + break; + default: // iframe-based. + pokeNativeViaIframe(); + } +} + +function pokeNativeViaXhr() { + // This prevents sending an XHR when there is already one being sent. + // This should happen only in rare circumstances (refer to unit tests). + if (execXhr && execXhr.readyState != 4) { + execXhr = null; + } + // Re-using the XHR improves exec() performance by about 10%. + execXhr = execXhr || new XMLHttpRequest(); + // Changing this to a GET will make the XHR reach the URIProtocol on 4.2. + // For some reason it still doesn't work though... + // Add a timestamp to the query param to prevent caching. + execXhr.open('HEAD', "/!gap_exec?" + (+new Date()), true); + if (!vcHeaderValue) { + vcHeaderValue = /.*\((.*)\)$/.exec(navigator.userAgent)[1]; + } + execXhr.setRequestHeader('vc', vcHeaderValue); + execXhr.setRequestHeader('rc', ++requestCount); + if (shouldBundleCommandJson()) { + execXhr.setRequestHeader('cmds', iOSExec.nativeFetchMessages()); + } + execXhr.send(null); +} + +function pokeNativeViaIframe() { + // CB-5488 - Don't attempt to create iframe before document.body is available. + if (!document.body) { + setTimeout(pokeNativeViaIframe); + return; + } + if (bridgeMode === jsToNativeModes.IFRAME_HASH_NO_PAYLOAD || bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + // TODO: This bridge mode doesn't properly support being removed from the DOM (CB-7735) + if (!execHashIframe) { + execHashIframe = document.createElement('iframe'); + execHashIframe.style.display = 'none'; + document.body.appendChild(execHashIframe); + // Hash changes don't work on about:blank, so switch it to file:///. + execHashIframe.contentWindow.history.replaceState(null, null, 'file:///#'); + } + // The delegate method is called only when the hash changes, so toggle it back and forth. + hashToggle = hashToggle ^ 3; + var hashValue = '%0' + hashToggle; + if (bridgeMode === jsToNativeModes.IFRAME_HASH_WITH_PAYLOAD) { + hashValue += iOSExec.nativeFetchMessages(); + } + execHashIframe.contentWindow.location.hash = hashValue; + } else { + // 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) { + pokeNative(); + } + }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire). + } +} + +iOSExec.jsToNativeModes = jsToNativeModes; + +iOSExec.setJsToNativeBridgeMode = function(mode) { + // Remove the iFrame since it may be no longer required, and its existence + // can trigger browser bugs. + // https://issues.apache.org/jira/browse/CB-593 + if (execIframe) { + if (execIframe.parentNode) { + execIframe.parentNode.removeChild(execIframe); + } + execIframe = null; + } + bridgeMode = mode; +}; + +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) { + return iOSExec.nativeEvalAndFetch(function() { + var success = status === 0 || status === 1; + var args = convertMessageToArgsNativeToJs(message); + cordova.callbackFromNative(callbackId, success, status, args, keepCallback); + }); +}; + +iOSExec.nativeEvalAndFetch = function(func) { + // This shouldn't be nested, but better to be safe. + isInContextOfEvalJs++; + try { + func(); + return iOSExec.nativeFetchMessages(); + } finally { + isInContextOfEvalJs--; + } +}; + +module.exports = iOSExec; + +}); + +// 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.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/init_b.js +define("cordova/init_b", function(require, exports, module) { + +var channel = require('cordova/channel'); +var cordova = require('cordova'); +var platform = require('cordova/platform'); +var utils = require('cordova/utils'); + +var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady]; + +// setting exec +cordova.exec = require('cordova/exec'); + +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.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(); +} + +// Call the platform-specific initialization. +platform.bootstrap && platform.bootstrap(); + +/** + * Create all cordova objects once native side is ready. + */ +channel.join(function() { + + 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'), + moduleMap = define.moduleMap, + symbolList, + 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; + } + var parts = symbolPath.split('.'); + var cur = context; + for (var i = 0, part; part = parts[i]; ++i) { + cur = cur[part] = cur[part] || {}; + } + return cur; +} + +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: src/ios/platform.js +define("cordova/platform", function(require, exports, module) { + +module.exports = { + id: 'ios', + bootstrap: function() { + require('cordova/channel').onNativeReady.fire(); + } +}; + + +}); + +// file: src/common/pluginloader.js +define("cordova/pluginloader", function(require, exports, module) { + +var modulemapper = require('cordova/modulemapper'); +var urlutil = require('cordova/urlutil'); + +// 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 = function(a) { + return utils.typeName(a) == 'Array'; +}; + +/** + * Returns an indication of whether the argument is a Date or not + */ +utils.isDate = function(d) { + return utils.typeName(d) == '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){ + if(!(i in retVal) || retVal[i] != obj[i]) { + retVal[i] = utils.clone(obj[i]); + } + } + return retVal; +}; + +/** + * Returns a wrapped version of the function + */ +utils.close = function(context, func, params) { + if (typeof params == 'undefined') { + return function() { + return func.apply(context, arguments); + }; + } else { + return function() { + return func.apply(context, params); + }; + } +}; + +/** + * 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); + } +}; + + +//------------------------------------------------------------------------------ +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; +} + + +}); + +window.cordova = require('cordova'); +// file: src/scripts/bootstrap.js + +require('cordova/init'); + +})();
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/www/cordova_plugins.js b/StoneIsland/platforms/ios/www/cordova_plugins.js new file mode 100644 index 00000000..cb7aedde --- /dev/null +++ b/StoneIsland/platforms/ios/www/cordova_plugins.js @@ -0,0 +1,102 @@ +cordova.define('cordova/plugin_list', function(require, exports, module) { +module.exports = [ + { + "file": "plugins/com.ionic.keyboard/www/keyboard.js", + "id": "com.ionic.keyboard.keyboard", + "clobbers": [ + "cordova.plugins.Keyboard" + ] + }, + { + "file": "plugins/cordova-plugin-console/www/logger.js", + "id": "cordova-plugin-console.logger", + "clobbers": [ + "cordova.logger" + ] + }, + { + "file": "plugins/cordova-plugin-console/www/console-via-logger.js", + "id": "cordova-plugin-console.console", + "clobbers": [ + "console" + ] + }, + { + "file": "plugins/cordova-plugin-device/www/device.js", + "id": "cordova-plugin-device.device", + "clobbers": [ + "device" + ] + }, + { + "file": "plugins/cordova-plugin-dialogs/www/notification.js", + "id": "cordova-plugin-dialogs.notification", + "merges": [ + "navigator.notification" + ] + }, + { + "file": "plugins/cordova-plugin-geolocation/www/Coordinates.js", + "id": "cordova-plugin-geolocation.Coordinates", + "clobbers": [ + "Coordinates" + ] + }, + { + "file": "plugins/cordova-plugin-geolocation/www/PositionError.js", + "id": "cordova-plugin-geolocation.PositionError", + "clobbers": [ + "PositionError" + ] + }, + { + "file": "plugins/cordova-plugin-geolocation/www/Position.js", + "id": "cordova-plugin-geolocation.Position", + "clobbers": [ + "Position" + ] + }, + { + "file": "plugins/cordova-plugin-geolocation/www/geolocation.js", + "id": "cordova-plugin-geolocation.geolocation", + "clobbers": [ + "navigator.geolocation" + ] + }, + { + "file": "plugins/cordova-plugin-network-information/www/network.js", + "id": "cordova-plugin-network-information.network", + "clobbers": [ + "navigator.connection", + "navigator.network.connection" + ] + }, + { + "file": "plugins/cordova-plugin-network-information/www/Connection.js", + "id": "cordova-plugin-network-information.Connection", + "clobbers": [ + "Connection" + ] + }, + { + "file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js", + "id": "cordova-plugin-splashscreen.SplashScreen", + "clobbers": [ + "navigator.splashscreen" + ] + } +]; +module.exports.metadata = +// TOP OF METADATA +{ + "cordova-plugin-whitelist": "1.0.0", + "com.ionic.keyboard": "1.0.4", + "cordova-plugin-console": "1.0.1", + "cordova-plugin-device": "1.0.1", + "cordova-plugin-dialogs": "1.1.1", + "cordova-plugin-geolocation": "1.0.1", + "cordova-plugin-network-information": "1.0.1", + "cordova-plugin-splashscreen": "2.1.0" +} +// BOTTOM OF METADATA +});
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/www/css/index.css b/StoneIsland/platforms/ios/www/css/index.css new file mode 100644 index 00000000..51daa797 --- /dev/null +++ b/StoneIsland/platforms/ios/www/css/index.css @@ -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. + */ +* { + -webkit-tap-highlight-color: rgba(0,0,0,0); /* make transparent link selection, adjust last value opacity 0 to 1.0 */ +} + +body { + -webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */ + -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */ + -webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */ + background-color:#E4E4E4; + background-image:linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%); + background-image:-webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%); + background-image:-ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%); + background-image:-webkit-gradient( + linear, + left top, + left bottom, + color-stop(0, #A7A7A7), + color-stop(0.51, #E4E4E4) + ); + background-attachment:fixed; + font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif; + font-size:12px; + height:100%; + margin:0px; + padding:0px; + text-transform:uppercase; + width:100%; +} + +/* Portrait layout (default) */ +.app { + background:url(../img/logo.png) no-repeat center top; /* 170px x 200px */ + position:absolute; /* position in the center of the screen */ + left:50%; + top:50%; + height:50px; /* text area height */ + width:225px; /* text area width */ + text-align:center; + padding:180px 0px 0px 0px; /* image height is 200px (bottom 20px are overlapped with text) */ + margin:-115px 0px 0px -112px; /* offset vertical: half of image height and text area height */ + /* offset horizontal: half of text area width */ +} + +/* Landscape layout (with min-width) */ +@media screen and (min-aspect-ratio: 1/1) and (min-width:400px) { + .app { + background-position:left center; + padding:75px 0px 75px 170px; /* padding-top + padding-bottom + text area = image height */ + margin:-90px 0px 0px -198px; /* offset vertical: half of image height */ + /* offset horizontal: half of image width and text area width */ + } +} + +h1 { + font-size:24px; + font-weight:normal; + margin:0px; + overflow:visible; + padding:0px; + text-align:center; +} + +.event { + border-radius:4px; + -webkit-border-radius:4px; + color:#FFFFFF; + font-size:12px; + margin:0px 30px; + padding:2px 0px; +} + +.event.listening { + background-color:#333333; + display:block; +} + +.event.received { + background-color:#4B946A; + display:none; +} + +@keyframes fade { + from { opacity: 1.0; } + 50% { opacity: 0.4; } + to { opacity: 1.0; } +} + +@-webkit-keyframes fade { + from { opacity: 1.0; } + 50% { opacity: 0.4; } + to { opacity: 1.0; } +} + +.blink { + animation:fade 3000ms infinite; + -webkit-animation:fade 3000ms infinite; +} diff --git a/StoneIsland/platforms/ios/www/img/logo.png b/StoneIsland/platforms/ios/www/img/logo.png Binary files differnew file mode 100644 index 00000000..9519e7dd --- /dev/null +++ b/StoneIsland/platforms/ios/www/img/logo.png diff --git a/StoneIsland/platforms/ios/www/index.html b/StoneIsland/platforms/ios/www/index.html new file mode 100644 index 00000000..09709bb9 --- /dev/null +++ b/StoneIsland/platforms/ios/www/index.html @@ -0,0 +1,28 @@ +<!doctype html> +<html> +<head> + <!-- + Customize this policy to fit your own app's needs. For more guidance, see: + https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy + Some notes: + * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication + * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly + * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: + * Enable inline JS: add 'unsafe-inline' to default-src + --> +<!-- + <meta http-equiv="Content-Security-Policy" content="default-src 'self' lvh.me lvh.me:5000 data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"> +--> + <meta name="format-detection" content="telephone=no"> + <meta name="msapplication-tap-highlight" content="no"> + <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> + <link rel="stylesheet" type="text/css" href="css/index.css"> + <title>Stone Island</title> +</head> +<body> + <script src="cordova.js"></script> + <script src="js/vendor/jquery-2.1.4.min.js"></script> + <script src="js/vendor/cookie.js"></script> + <script src="js/index.js"></script> +</body> +</html> diff --git a/StoneIsland/platforms/ios/www/js/index.js b/StoneIsland/platforms/ios/www/js/index.js new file mode 100644 index 00000000..2875c90b --- /dev/null +++ b/StoneIsland/platforms/ios/www/js/index.js @@ -0,0 +1,37 @@ +var app = (function(){ + + var app = {} + app.init = function(){ + app.bind() + } + app.bind = function(){ + document.addEventListener('deviceready', app.ready, false) + } + app.ready = function(){ + cookies.setItem("testing", "testing", 60*60*24*365) + console.log(document.cookie) + $.ajax({ + url: "http://lvh.me:5000/", + xhrFields: { + withCredentials: true + }, + success: function(){ + app.again() + } + }) + document.write("duh") + } + app.again = function(){ + $.ajax({ + url: "http://lvh.me:5000/", + xhrFields: { + withCredentials: true + }, + success: function(){ + } + }) + } + + app.init() + +})() diff --git a/StoneIsland/platforms/ios/www/js/vendor/cookie.js b/StoneIsland/platforms/ios/www/js/vendor/cookie.js new file mode 100644 index 00000000..ad160ef1 --- /dev/null +++ b/StoneIsland/platforms/ios/www/js/vendor/cookie.js @@ -0,0 +1,63 @@ +/*\ +|*| +|*| :: cookies.js :: +|*| +|*| A complete cookies reader/writer framework with full unicode support. +|*| +|*| Revision #1 - September 4, 2014 +|*| +|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie +|*| https://developer.mozilla.org/User:fusionchess +|*| +|*| This framework is released under the GNU Public License, version 3 or later. +|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html +|*| +|*| Syntaxes: +|*| +|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) +|*| * docCookies.getItem(name) +|*| * docCookies.removeItem(name[, path[, domain]]) +|*| * docCookies.hasItem(name) +|*| * docCookies.keys() +|*| +\*/ + +var cookies = { + getItem: function (sKey) { + if (!sKey) { return null; } + return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; + }, + setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { + if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } + var sExpires = ""; + if (vEnd) { + switch (vEnd.constructor) { + case Number: + sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; + break; + case String: + sExpires = "; expires=" + vEnd; + break; + case Date: + sExpires = "; expires=" + vEnd.toUTCString(); + break; + } + } + document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); + return true; + }, + removeItem: function (sKey, sPath, sDomain) { + if (!this.hasItem(sKey)) { return false; } + document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); + return true; + }, + hasItem: function (sKey) { + if (!sKey) { return false; } + return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); + }, + keys: function () { + var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); + for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } + return aKeys; + } +};
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/www/js/vendor/jquery-2.1.4.min.js b/StoneIsland/platforms/ios/www/js/vendor/jquery-2.1.4.min.js new file mode 100644 index 00000000..49990d6e --- /dev/null +++ b/StoneIsland/platforms/ios/www/js/vendor/jquery-2.1.4.min.js @@ -0,0 +1,4 @@ +/*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){ +return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function ya(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),f.removeChild(c),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",ta(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xa(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fa(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ba.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wa(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Ja(this,!0)},hide:function(){return Ja(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Ka.propHooks.scrollTop=Ka.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||ta(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Na.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ta(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ua(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wa(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:La||Sa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xa,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xa(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pa.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Ya,Za,$a=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Za:Ya)), +void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cb=n.now(),db=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function rb(a,b,c,d){var e={},f=a===mb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function sb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function tb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function ub(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=gb.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+nb+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=rb(mb,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=tb(k,v,f)),u=ub(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Cb[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Fb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Jb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Jb(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n}); diff --git a/StoneIsland/platforms/ios/www/js/vendor/xhr.js b/StoneIsland/platforms/ios/www/js/vendor/xhr.js new file mode 100644 index 00000000..715d1c60 --- /dev/null +++ b/StoneIsland/platforms/ios/www/js/vendor/xhr.js @@ -0,0 +1,35 @@ +var XMLHTTPRequest = (function(){ + + var xhr = function (opt) { + this.status = 0 + this.readyState = 0 + this.response = "" + this.responseText = "" + this.responseType = "" // "" arraybuffer blob document json text + this.responseXML = "" + this.statusText = "" + this.timeout = 0 + this.onreadystatechange = function(){} + this.ontimeout = function(){} + this.onload = function(){} + this.headers = [] + this.upload = {} + this.withCredentials = false + } + xhr.prototype.open = function(method, url, async, user, password){ + } + xhr.prototype.abort = function(){ + } + xhr.prototype.getAllResponseHeaders = function(){ + } + xhr.prototype.getResponseHeader = function(){ + } + xhr.prototype.overrideMimeType = function(){ + } + xhr.prototype.setRequestHeader = function(key, value){ + this.headers.push({ key: key, value: value }) + } + xhr.prototype.send = function(data){ + } + +})()
\ No newline at end of file diff --git a/StoneIsland/platforms/ios/www/plugins/com.ionic.keyboard/www/keyboard.js b/StoneIsland/platforms/ios/www/plugins/com.ionic.keyboard/www/keyboard.js new file mode 100644 index 00000000..7d30ba59 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/com.ionic.keyboard/www/keyboard.js @@ -0,0 +1,39 @@ +cordova.define("com.ionic.keyboard.keyboard", function(require, exports, module) { +var argscheck = require('cordova/argscheck'), + utils = require('cordova/utils'), + exec = require('cordova/exec'); + + +var Keyboard = function() { +}; + +Keyboard.hideKeyboardAccessoryBar = function(hide) { + exec(null, null, "Keyboard", "hideKeyboardAccessoryBar", [hide]); +}; + +Keyboard.close = function() { + exec(null, null, "Keyboard", "close", []); +}; + +Keyboard.show = function() { + exec(null, null, "Keyboard", "show", []); +}; + +Keyboard.disableScroll = function(disable) { + exec(null, null, "Keyboard", "disableScroll", [disable]); +}; + +/* +Keyboard.styleDark = function(dark) { + exec(null, null, "Keyboard", "styleDark", [dark]); +}; +*/ + +Keyboard.isVisible = false; + +module.exports = Keyboard; + + + + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-console/www/console-via-logger.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-console/www/console-via-logger.js new file mode 100644 index 00000000..0ce8cea8 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-console/www/console-via-logger.js @@ -0,0 +1,189 @@ +cordova.define("cordova-plugin-console.console", 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 logger = require("./logger"); +var utils = require("cordova/utils"); + +//------------------------------------------------------------------------------ +// 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/StoneIsland/platforms/ios/www/plugins/cordova-plugin-console/www/logger.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-console/www/logger.js new file mode 100644 index 00000000..7a9a75d3 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-console/www/logger.js @@ -0,0 +1,357 @@ +cordova.define("cordova-plugin-console.logger", 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. + * +*/ + +//------------------------------------------------------------------------------ +// 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 utils = require('cordova/utils'); + +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/StoneIsland/platforms/ios/www/plugins/cordova-plugin-device/www/device.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-device/www/device.js new file mode 100644 index 00000000..023bafd2 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-device/www/device.js @@ -0,0 +1,81 @@ +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'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + exec = require('cordova/exec'), + 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; + + 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.manufacturer = info.manufacturer || '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/StoneIsland/platforms/ios/www/plugins/cordova-plugin-dialogs/www/notification.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-dialogs/www/notification.js new file mode 100644 index 00000000..ea97eefb --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-dialogs/www/notification.js @@ -0,0 +1,114 @@ +cordova.define("cordova-plugin-dialogs.notification", 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 platform = require('cordova/platform'); + +/** + * Provides access to notifications on the device. + */ + +module.exports = { + + /** + * Open a native alert dialog, with a customizable title and button text. + * + * @param {String} message Message to print in the body of the alert + * @param {Function} completeCallback The callback that is called when user clicks on a button. + * @param {String} title Title of the alert dialog (default: Alert) + * @param {String} buttonLabel Label of the close button (default: OK) + */ + alert: function(message, completeCallback, title, buttonLabel) { + var _title = (title || "Alert"); + var _buttonLabel = (buttonLabel || "OK"); + exec(completeCallback, null, "Notification", "alert", [message, _title, _buttonLabel]); + }, + + /** + * Open a native confirm dialog, with a customizable title and button text. + * The result that the user selects is returned to the result callback. + * + * @param {String} message Message to print in the body of the alert + * @param {Function} resultCallback The callback that is called when user clicks on a button. + * @param {String} title Title of the alert dialog (default: Confirm) + * @param {Array} buttonLabels Array of the labels of the buttons (default: ['OK', 'Cancel']) + */ + confirm: function(message, resultCallback, title, buttonLabels) { + var _title = (title || "Confirm"); + var _buttonLabels = (buttonLabels || ["OK", "Cancel"]); + + // Strings are deprecated! + if (typeof _buttonLabels === 'string') { + console.log("Notification.confirm(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array)."); + } + + // Some platforms take an array of button label names. + // Other platforms take a comma separated list. + // For compatibility, we convert to the desired type based on the platform. + if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" || + platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu" || + platform.id == "windows8" || platform.id == "windows") { + + if (typeof _buttonLabels === 'string') { + _buttonLabels = _buttonLabels.split(","); // not crazy about changing the var type here + } + } else { + if (Array.isArray(_buttonLabels)) { + var buttonLabelArray = _buttonLabels; + _buttonLabels = buttonLabelArray.toString(); + } + } + exec(resultCallback, null, "Notification", "confirm", [message, _title, _buttonLabels]); + }, + + /** + * Open a native prompt dialog, with a customizable title and button text. + * The following results are returned to the result callback: + * buttonIndex Index number of the button selected. + * input1 The text entered in the prompt dialog box. + * + * @param {String} message Dialog message to display (default: "Prompt message") + * @param {Function} resultCallback The callback that is called when user clicks on a button. + * @param {String} title Title of the dialog (default: "Prompt") + * @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"]) + * @param {String} defaultText Textbox input value (default: empty string) + */ + prompt: function(message, resultCallback, title, buttonLabels, defaultText) { + var _message = (message || "Prompt message"); + var _title = (title || "Prompt"); + var _buttonLabels = (buttonLabels || ["OK","Cancel"]); + var _defaultText = (defaultText || ""); + exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]); + }, + + /** + * Causes the device to beep. + * On Android, the default notification ringtone is played "count" times. + * + * @param {Integer} count The number of beeps. + */ + beep: function(count) { + var defaultedCount = count || 1; + exec(null, null, "Notification", "beep", [ defaultedCount ]); + } +}; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/Coordinates.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/Coordinates.js new file mode 100644 index 00000000..f7255659 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/Coordinates.js @@ -0,0 +1,71 @@ +cordova.define("cordova-plugin-geolocation.Coordinates", 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. + * +*/ + +/** + * This class contains position information. + * @param {Object} lat + * @param {Object} lng + * @param {Object} alt + * @param {Object} acc + * @param {Object} head + * @param {Object} vel + * @param {Object} altacc + * @constructor + */ +var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) { + /** + * The latitude of the position. + */ + this.latitude = lat; + /** + * The longitude of the position, + */ + this.longitude = lng; + /** + * The accuracy of the position. + */ + this.accuracy = acc; + /** + * The altitude of the position. + */ + this.altitude = (alt !== undefined ? alt : null); + /** + * The direction the device is moving at the position. + */ + this.heading = (head !== undefined ? head : null); + /** + * The velocity with which the device is moving at the position. + */ + this.speed = (vel !== undefined ? vel : null); + + if (this.speed === 0 || this.speed === null) { + this.heading = NaN; + } + + /** + * The altitude accuracy of the position. + */ + this.altitudeAccuracy = (altacc !== undefined) ? altacc : null; +}; + +module.exports = Coordinates; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/Position.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/Position.js new file mode 100644 index 00000000..206bf8b4 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/Position.js @@ -0,0 +1,35 @@ +cordova.define("cordova-plugin-geolocation.Position", 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 Coordinates = require('./Coordinates'); + +var Position = function(coords, timestamp) { + if (coords) { + this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.velocity, coords.altitudeAccuracy); + } else { + this.coords = new Coordinates(); + } + this.timestamp = (timestamp !== undefined) ? timestamp : new Date(); +}; + +module.exports = Position; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/PositionError.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/PositionError.js new file mode 100644 index 00000000..11ffe491 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/PositionError.js @@ -0,0 +1,40 @@ +cordova.define("cordova-plugin-geolocation.PositionError", 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. + * +*/ + +/** + * Position error object + * + * @constructor + * @param code + * @param message + */ +var PositionError = function(code, message) { + this.code = code || null; + this.message = message || ''; +}; + +PositionError.PERMISSION_DENIED = 1; +PositionError.POSITION_UNAVAILABLE = 2; +PositionError.TIMEOUT = 3; + +module.exports = PositionError; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/geolocation.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/geolocation.js new file mode 100644 index 00000000..ec9bb6e8 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-geolocation/www/geolocation.js @@ -0,0 +1,213 @@ +cordova.define("cordova-plugin-geolocation.geolocation", 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'), + utils = require('cordova/utils'), + exec = require('cordova/exec'), + PositionError = require('./PositionError'), + Position = require('./Position'); + +var timers = {}; // list of timers in use + +// Returns default params, overrides if provided with values +function parseParameters(options) { + var opt = { + maximumAge: 0, + enableHighAccuracy: false, + timeout: Infinity + }; + + if (options) { + if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) { + opt.maximumAge = options.maximumAge; + } + if (options.enableHighAccuracy !== undefined) { + opt.enableHighAccuracy = options.enableHighAccuracy; + } + if (options.timeout !== undefined && !isNaN(options.timeout)) { + if (options.timeout < 0) { + opt.timeout = 0; + } else { + opt.timeout = options.timeout; + } + } + } + + return opt; +} + +// Returns a timeout failure, closed over a specified timeout value and error callback. +function createTimeout(errorCallback, timeout) { + var t = setTimeout(function() { + clearTimeout(t); + t = null; + errorCallback({ + code:PositionError.TIMEOUT, + message:"Position retrieval timed out." + }); + }, timeout); + return t; +} + +var geolocation = { + lastPosition:null, // reference to last known (cached) position returned + /** + * Asynchronously acquires the current position. + * + * @param {Function} successCallback The function to call when the position data is available + * @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL) + * @param {PositionOptions} options The options for getting the position data. (OPTIONAL) + */ + getCurrentPosition:function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); + options = parseParameters(options); + + // Timer var that will fire an error callback if no position is retrieved from native + // before the "timeout" param provided expires + var timeoutTimer = {timer:null}; + + var win = function(p) { + clearTimeout(timeoutTimer.timer); + if (!(timeoutTimer.timer)) { + // Timeout already happened, or native fired error callback for + // this geo request. + // Don't continue with success callback. + return; + } + var pos = new Position( + { + latitude:p.latitude, + longitude:p.longitude, + altitude:p.altitude, + accuracy:p.accuracy, + heading:p.heading, + velocity:p.velocity, + altitudeAccuracy:p.altitudeAccuracy + }, + (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))) + ); + geolocation.lastPosition = pos; + successCallback(pos); + }; + var fail = function(e) { + clearTimeout(timeoutTimer.timer); + timeoutTimer.timer = null; + var err = new PositionError(e.code, e.message); + if (errorCallback) { + errorCallback(err); + } + }; + + // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just + // fire the success callback with the cached position. + if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) { + successCallback(geolocation.lastPosition); + // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object. + } else if (options.timeout === 0) { + fail({ + code:PositionError.TIMEOUT, + message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter." + }); + // Otherwise we have to call into native to retrieve a position. + } else { + if (options.timeout !== Infinity) { + // If the timeout value was not set to Infinity (default), then + // set up a timeout function that will fire the error callback + // if no successful position was retrieved before timeout expired. + timeoutTimer.timer = createTimeout(fail, options.timeout); + } else { + // This is here so the check in the win function doesn't mess stuff up + // may seem weird but this guarantees timeoutTimer is + // always truthy before we call into native + timeoutTimer.timer = true; + } + exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]); + } + return timeoutTimer; + }, + /** + * Asynchronously watches the geolocation for changes to geolocation. When a change occurs, + * the successCallback is called with the new location. + * + * @param {Function} successCallback The function to call each time the location data is available + * @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL) + * @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL) + * @return String The watch id that must be passed to #clearWatch to stop watching. + */ + watchPosition:function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); + options = parseParameters(options); + + var id = utils.createUUID(); + + // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition + timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options); + + var fail = function(e) { + clearTimeout(timers[id].timer); + var err = new PositionError(e.code, e.message); + if (errorCallback) { + errorCallback(err); + } + }; + + var win = function(p) { + clearTimeout(timers[id].timer); + if (options.timeout !== Infinity) { + timers[id].timer = createTimeout(fail, options.timeout); + } + var pos = new Position( + { + latitude:p.latitude, + longitude:p.longitude, + altitude:p.altitude, + accuracy:p.accuracy, + heading:p.heading, + velocity:p.velocity, + altitudeAccuracy:p.altitudeAccuracy + }, + (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))) + ); + geolocation.lastPosition = pos; + successCallback(pos); + }; + + exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]); + + return id; + }, + /** + * Clears the specified heading watch. + * + * @param {String} id The ID of the watch returned from #watchPosition + */ + clearWatch:function(id) { + if (id && timers[id] !== undefined) { + clearTimeout(timers[id].timer); + timers[id].timer = false; + exec(null, null, "Geolocation", "clearWatch", [id]); + } + } +}; + +module.exports = geolocation; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-network-information/www/Connection.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-network-information/www/Connection.js new file mode 100644 index 00000000..1450e953 --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-network-information/www/Connection.js @@ -0,0 +1,36 @@ +cordova.define("cordova-plugin-network-information.Connection", 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. + * +*/ + +/** + * Network status + */ +module.exports = { + UNKNOWN: "unknown", + ETHERNET: "ethernet", + WIFI: "wifi", + CELL_2G: "2g", + CELL_3G: "3g", + CELL_4G: "4g", + CELL:"cellular", + NONE: "none" +}; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-network-information/www/network.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-network-information/www/network.js new file mode 100644 index 00000000..bfac2e3f --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-network-information/www/network.js @@ -0,0 +1,93 @@ +cordova.define("cordova-plugin-network-information.network", 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'), + cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'); + +// Link the onLine property with the Cordova-supplied network info. +// This works because we clobber the navigator object with our own +// object in bootstrap.js. +// Browser platform do not need to define this property, because +// it is already supported by modern browsers +if (cordova.platformId !== 'browser' && typeof navigator != 'undefined') { + utils.defineGetter(navigator, 'onLine', function() { + return this.connection.type != 'none'; + }); +} + +function NetworkConnection() { + this.type = 'unknown'; +} + +/** + * Get connection info + * + * @param {Function} successCallback The function to call when the Connection data is available + * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL) + */ +NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) { + exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []); +}; + +var me = new NetworkConnection(); +var timerId = null; +var timeout = 500; + +channel.createSticky('onCordovaConnectionReady'); +channel.waitForInitialization('onCordovaConnectionReady'); + +channel.onCordovaReady.subscribe(function() { + me.getInfo(function(info) { + me.type = info; + if (info === "none") { + // set a timer if still offline at the end of timer send the offline event + timerId = setTimeout(function(){ + cordova.fireDocumentEvent("offline"); + timerId = null; + }, timeout); + } else { + // If there is a current offline event pending clear it + if (timerId !== null) { + clearTimeout(timerId); + timerId = null; + } + cordova.fireDocumentEvent("online"); + } + + // should only fire this once + if (channel.onCordovaConnectionReady.state !== 2) { + channel.onCordovaConnectionReady.fire(); + } + }, + function (e) { + // If we can't get the network info we should still tell Cordova + // to fire the deviceready event. + if (channel.onCordovaConnectionReady.state !== 2) { + channel.onCordovaConnectionReady.fire(); + } + console.log("Error initializing Network Connection: " + e); + }); +}); + +module.exports = me; + +}); diff --git a/StoneIsland/platforms/ios/www/plugins/cordova-plugin-splashscreen/www/splashscreen.js b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-splashscreen/www/splashscreen.js new file mode 100644 index 00000000..0e6a10af --- /dev/null +++ b/StoneIsland/platforms/ios/www/plugins/cordova-plugin-splashscreen/www/splashscreen.js @@ -0,0 +1,35 @@ +cordova.define("cordova-plugin-splashscreen.SplashScreen", 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 splashscreen = { + show:function() { + exec(null, null, "SplashScreen", "show", []); + }, + hide:function() { + exec(null, null, "SplashScreen", "hide", []); + } +}; + +module.exports = splashscreen; + +}); diff --git a/StoneIsland/platforms/platforms.json b/StoneIsland/platforms/platforms.json new file mode 100644 index 00000000..f0acd064 --- /dev/null +++ b/StoneIsland/platforms/platforms.json @@ -0,0 +1,3 @@ +{ + "ios": "3.8.0" +}
\ No newline at end of file diff --git a/StoneIsland/plugins/com.ionic.keyboard/LICENSE b/StoneIsland/plugins/com.ionic.keyboard/LICENSE new file mode 100644 index 00000000..d6f545b8 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Drifty Co. + + Licensed 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. diff --git a/StoneIsland/plugins/com.ionic.keyboard/README.md b/StoneIsland/plugins/com.ionic.keyboard/README.md new file mode 100644 index 00000000..63f70012 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/README.md @@ -0,0 +1,123 @@ +Keyboard +====== + +The `cordova.plugins.Keyboard` object provides functions to make interacting with the keyboard easier, and fires events to indicate that the keyboard will hide/show. + + cordova plugin add com.ionic.keyboard + +Methods +------- + +- cordova.plugins.Keyboard.hideKeyboardAccessoryBar +- cordova.plugins.Keyboard.close +- cordova.plugins.Keyboard.disableScroll +- cordova.plugins.Keyboard.show + +Properties +-------- + +- cordova.plugins.Keyboard.isVisible + +Events +-------- + +These events are fired on the window. + +- native.keyboardshow + * A number `keyboardHeight` is given on the event object, which is the pixel height of the keyboard. +- native.keyboardhide + +Keyboard.hideKeyboardAccessoryBar +================= + +Hide the keyboard accessory bar with the next, previous and done buttons. + + cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); + cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false); + +Supported Platforms +------------------- + +- iOS + + +Keyboard.close +================= + +Close the keyboard if it is open. + + cordova.plugins.Keyboard.close(); + +Supported Platforms +------------------- + +- iOS, Android, Blackberry 10 + + +Keyboard.disableScroll +================= + +Disable native scrolling, useful if you are using JavaScript to scroll + + cordova.plugins.Keyboard.disableScroll(true); + cordova.plugins.Keyboard.disableScroll(false); + +Supported Platforms +------------------- + +- iOS + +Keyboard.show +================= + +Force keyboard to be shown on Android. This typically helps if autofocus on a text element does not pop up the keyboard automatically + + cordova.plugins.Keyboard.show(); + +Supported Platforms + +- Android, Blackberry 10 + +native.keyboardshow +================= + +This event fires when the keyboard will be shown + + window.addEventListener('native.keyboardshow', keyboardShowHandler); + + function keyboardShowHandler(e){ + alert('Keyboard height is: ' + e.keyboardHeight); + } + +Properties +----------- + +keyboardHeight: the height of the keyboard in pixels + + +Supported Platforms +------------------- + +- iOS, Android, Blackberry 10 + + +native.keyboardhide +================= + +This event fires when the keyboard will hide + + window.addEventListener('native.keyboardhide', keyboardHideHandler); + + function keyboardHideHandler(e){ + alert('Goodnight, sweet prince'); + } + +Properties +----------- + +None + +Supported Platforms +------------------- + +- iOS, Android, Blackberry 10 diff --git a/StoneIsland/plugins/com.ionic.keyboard/package.json b/StoneIsland/plugins/com.ionic.keyboard/package.json new file mode 100644 index 00000000..4dd54150 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/package.json @@ -0,0 +1,19 @@ +{ + "version": "1.0.4", + "name": "com.ionic.keyboard", + "cordova_name": "Keyboard", + "description": "Ionic Keyboard Plugin", + "license": "Apache 2.0", + "repo": "https://github.com/driftyco/ionic-plugins-keyboard.git", + "issue": "https://github.com/driftyco/ionic-plugins-keyboard/issues", + "keywords": [ + "Ionic", + "keyboard" + ], + "platforms": [ + "android", + "ios", + "blackberry10" + ], + "engines": [] +}
\ No newline at end of file diff --git a/StoneIsland/plugins/com.ionic.keyboard/plugin.xml b/StoneIsland/plugins/com.ionic.keyboard/plugin.xml new file mode 100644 index 00000000..06688915 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/plugin.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="com.ionic.keyboard" + version="1.0.4"> + <name>Keyboard</name> + <description>Ionic Keyboard Plugin</description> + <license>Apache 2.0</license> + <keywords>Ionic,keyboard</keywords> + <repo>https://github.com/driftyco/ionic-plugins-keyboard.git</repo> + <issue>https://github.com/driftyco/ionic-plugins-keyboard/issues</issue> + + <js-module src="www/keyboard.js" name="keyboard"> + <clobbers target="cordova.plugins.Keyboard" /> + </js-module> + + <!-- android --> + <platform name="android"> + + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="Keyboard"> + <param name="android-package" value="com.ionic.keyboard.IonicKeyboard" /> + <param name="onload" value="true" /> + </feature> + </config-file> + + <source-file src="src/android/IonicKeyboard.java" target-dir="src/com/ionic/keyboard" /> + </platform> + + <!-- ios --> + <platform name="ios"> + <config-file target="config.xml" parent="/*"> + <feature name="Keyboard"> + <param name="ios-package" value="IonicKeyboard" onload="true" /> + </feature> + </config-file> + + <header-file src="src/ios/IonicKeyboard.h" /> + <source-file src="src/ios/IonicKeyboard.m" /> + <header-file src="src/ios/UIWebViewExtension.h" /> + <source-file src="src/ios/UIWebViewExtension.m" /> + </platform> + + <!-- blackberry10 --> + <platform name="blackberry10"> + <source-file src="src/blackberry10/index.js" target-dir='Keyboard' /> + <lib-file src="src/blackberry10/native/device/libKeyboard.so" arch="device"/> + <lib-file src="src/blackberry10/native/simulator/libKeyboard.so" arch="simulator"/> + <config-file target="www/config.xml" parent="/widget"> + <feature name="Keyboard" value="com.ionic.keyboard"/> + + </config-file> + </platform> + +</plugin> diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/android/IonicKeyboard.java b/StoneIsland/plugins/com.ionic.keyboard/src/android/IonicKeyboard.java new file mode 100644 index 00000000..deb914ab --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/android/IonicKeyboard.java @@ -0,0 +1,96 @@ +package com.ionic.keyboard; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaWebView; +import org.apache.cordova.PluginResult.Status; +import org.json.JSONArray; +import org.json.JSONException; + +import android.content.Context; +import android.graphics.Rect; +import android.util.DisplayMetrics; +import android.view.View; +import android.view.ViewTreeObserver.OnGlobalLayoutListener; +import android.view.inputmethod.InputMethodManager; + +public class IonicKeyboard extends CordovaPlugin{ + + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + + //calculate density-independent pixels (dp) + //http://developer.android.com/guide/practices/screens_support.html + DisplayMetrics dm = new DisplayMetrics(); + cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); + final float density = dm.density; + + final CordovaWebView appView = webView; + + //http://stackoverflow.com/a/4737265/1091751 detect if keyboard is showing + final View rootView = cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content).getRootView(); + OnGlobalLayoutListener list = new OnGlobalLayoutListener() { + int previousHeightDiff = 0; + @Override + public void onGlobalLayout() { + Rect r = new Rect(); + //r will be populated with the coordinates of your view that area still visible. + rootView.getWindowVisibleDisplayFrame(r); + + int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top); + int pixelHeightDiff = (int)(heightDiff / density); + if (pixelHeightDiff > 100 && pixelHeightDiff != previousHeightDiff) { // if more than 100 pixels, its probably a keyboard... + appView.sendJavascript("cordova.plugins.Keyboard.isVisible = true"); + appView.sendJavascript("cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight':" + Integer.toString(pixelHeightDiff)+"});"); + + //deprecated + appView.sendJavascript("cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight':" + Integer.toString(pixelHeightDiff)+"});"); + } + else if ( pixelHeightDiff != previousHeightDiff && ( previousHeightDiff - pixelHeightDiff ) > 100 ){ + appView.sendJavascript("cordova.plugins.Keyboard.isVisible = false"); + appView.sendJavascript("cordova.fireWindowEvent('native.keyboardhide')"); + + //deprecated + appView.sendJavascript("cordova.fireWindowEvent('native.hidekeyboard')"); + } + previousHeightDiff = pixelHeightDiff; + } + }; + + rootView.getViewTreeObserver().addOnGlobalLayoutListener(list); + } + + public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { + if ("close".equals(action)) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + //http://stackoverflow.com/a/7696791/1091751 + InputMethodManager inputManager = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); + View v = cordova.getActivity().getCurrentFocus(); + + if (v == null) { + callbackContext.error("No current focus"); + } else { + inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); + callbackContext.success(); // Thread-safe. + } + } + }); + return true; + } + if ("show".equals(action)) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + ((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); + callbackContext.success(); // Thread-safe. + } + }); + return true; + } + return false; // Returning false results in a "MethodNotFound" error. + } + + +} + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/index.js b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/index.js new file mode 100644 index 00000000..40294158 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/index.js @@ -0,0 +1,135 @@ + + +var keyboard, + resultObjs = {}, + threadCallback = null, + _utils = require("../../lib/utils"); + _event = require("../../lib/event"); + _webview = require("../../lib/webview"); + + + + +module.exports = { + + // Code can be declared and used outside the module.exports object, + // but any functions to be called by client.js need to be declared + // here in this object. + + // These methods call into JNEXT.Keyboard which handles the + // communication through the JNEXT plugin to keyboard_js.cpp + startService: function (success, fail, args, env) { + var result = new PluginResult(args, env); + + result.ok(keyboard.getInstance().startService(), false); + }, + show: function (success, fail, args, env) { + var result = new PluginResult(args, env); + + result.ok(keyboard.getInstance().showKeyboard(), false); + }, + close: function (success, fail, args, env) { + var result = new PluginResult(args, env); + + result.ok(keyboard.getInstance().closeKeyboard(), false); + } +}; + +keyboardShow = function(a){ + _webview.executeJavascript("cordova.plugins.Keyboard.isVisible = true"); + _webview.executeJavascript("cordova.fireDocumentEvent('native.keyboardshow',"+a+")"); + +} +keyboardHide = function(){ + _webview.executeJavascript("cordova.plugins.Keyboard.isVisible = false"); + _webview.executeJavascript("cordova.fireDocumentEvent('native.keyboardhide','')"); + +} +onStart = function() { + _webview.executeJavascript("cordova.exec("+null+", "+null+", 'Keyboard', 'startService', '')"); + } + +setTimeout(onStart,2000); + +/////////////////////////////////////////////////////////////////// +// JavaScript wrapper for JNEXT plugin for connection +/////////////////////////////////////////////////////////////////// + +JNEXT.Keyboard = function () { + var self = this, + hasInstance = false; + + self.getId = function () { + return self.m_id; + }; + + self.init = function () { + if (!JNEXT.require("libKeyboard")) { + return false; + } + + self.m_id = JNEXT.createObject("libKeyboard.Keyboard_JS"); + + if (self.m_id === "") { + return false; + } + + JNEXT.registerEvents(self); + }; + + // ************************ + // Enter your methods here + // ************************ + + // calls into InvokeMethod(string command) in keyboard_js.cpp + self.startService = function () { + return JNEXT.invoke(self.m_id, "startService"); + }; + self.showKeyboard = function () { + return JNEXT.invoke(self.m_id, "showKeyboard"); + }; + self.closeKeyboard = function () { + return JNEXT.invoke(self.m_id, "closeKeyboard"); + }; + + self.onEvent = function (strData) { // Fired by the Event framework (used by asynchronous callbacks) + var arData = strData.split(" "), + strEventDesc = arData[0], + jsonData; + + if (strEventDesc === "native.keyboardshow") { + jsonData = arData.slice(1, arData.length).join(" "); + keyboardShow(jsonData); + + } + else if (strEventDesc === "native.keyboardhide") { + keyboardHide(); + } + + }; + + // Thread methods + self.keyboardStartThread = function (callbackId) { + return JNEXT.invoke(self.m_id, "keyboardStartThread " + callbackId); + }; + self.keyboardStopThread = function () { + return JNEXT.invoke(self.m_id, "keyboardStopThread"); + }; + + // ************************ + // End of methods to edit + // ************************ + self.m_id = ""; + + self.getInstance = function () { + if (!hasInstance) { + hasInstance = true; + self.init(); + } + return self; + }; + +}; + +keyboard = new JNEXT.Keyboard(); + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/.cproject b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/.cproject new file mode 100644 index 00000000..7b118eec --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/.cproject @@ -0,0 +1,222 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> + <storageModule moduleId="org.eclipse.cdt.core.settings"> + <cconfiguration id="com.qnx.qcc.configuration.sharedLib.release.608922875.1009704567"> + <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="com.qnx.qcc.configuration.sharedLib.release.608922875.1009704567" moduleId="org.eclipse.cdt.core.settings" name="device"> + <externalSettings> + <externalSetting> + <entry flags="VALUE_WORKSPACE_PATH" kind="includePath" name="/Cordova-Keyboard"/> + <entry flags="VALUE_WORKSPACE_PATH" kind="libraryPath" name="/Cordova-Keyboard/device"/> + <entry flags="RESOLVED" kind="libraryFile" name="Cordova-Keyboard" srcPrefixMapping="" srcRootPath=""/> + </externalSetting> + </externalSettings> + <extensions> + <extension id="com.qnx.tools.ide.qde.core.QDELinkerErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="com.qnx.tools.ide.qde.core.QDEBynaryParser" point="org.eclipse.cdt.core.BinaryParser"/> + </extensions> + </storageModule> + <storageModule moduleId="cdtBuildSystem" version="4.0.0"> + <configuration artifactExtension="so" artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.sharedLib" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.sharedLib" description="" id="com.qnx.qcc.configuration.sharedLib.release.608922875.1009704567" name="device" parent="com.qnx.qcc.configuration.sharedLib.release"> + <folderInfo id="com.qnx.qcc.configuration.sharedLib.release.608922875.1009704567." name="/" resourcePath=""> + <toolChain id="com.qnx.qcc.toolChain.2215983" name="QNX QCC" superClass="com.qnx.qcc.toolChain"> + <option id="com.qnx.qcc.option.cpu.315540759" name="Target CPU:" superClass="com.qnx.qcc.option.cpu" value="com.qnx.qcc.option.gen.cpu.armle-v7" valueType="enumerated"/> + <targetPlatform archList="all" binaryParser="com.qnx.tools.ide.qde.core.QDEBynaryParser" id="com.qnx.qcc.targetPlatform.1359109141" osList="all" superClass="com.qnx.qcc.targetPlatform"/> + <builder buildPath="${workspace_loc:/Keyboard/Device-Release}" id="com.qnx.nto.938326560" keepEnvironmentInBuildfile="false" name="CDT Internal Builder" superClass="com.qnx.nto"/> + <tool id="com.qnx.qcc.tool.compiler.242697771" name="QCC Compiler" superClass="com.qnx.qcc.tool.compiler"> + <option id="com.qnx.qcc.option.compiler.shared.553244928" name="Shared (-shared)" superClass="com.qnx.qcc.option.compiler.shared" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.compiler.optlevel.2070537906" name="Optimization Level" superClass="com.qnx.qcc.option.compiler.optlevel" value="com.qnx.qcc.option.compiler.optlevel.2" valueType="enumerated"/> + <option id="com.qnx.qcc.option.compiler.includePath.1483355415" name="Include Directories (-I)" superClass="com.qnx.qcc.option.compiler.includePath" valueType="includePath"> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/bb"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/qt4/QtCore"/> + <listOptionValue builtIn="false" value="${workspace_loc:/${ProjName}/public}"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/qt4"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/freetype2"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/../target-override/usr/include"/> + </option> + <option id="com.qnx.qcc.option.compiler.security.9625963" name="Enhanced Security (-fstack-protector-strong)" superClass="com.qnx.qcc.option.compiler.security" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.compiler.defines.872099896" name="Defines (-D)" superClass="com.qnx.qcc.option.compiler.defines" valueType="definedSymbols"> + <listOptionValue builtIn="false" value="_FORTIFY_SOURCE=2"/> + </option> + <option id="com.qnx.qcc.option.compiler.qccoptions.1015003128" name="QCC Options" superClass="com.qnx.qcc.option.compiler.qccoptions" valueType="stringList"> + <listOptionValue builtIn="false" value="-frecord-gcc-switches"/> + </option> + <inputType id="com.qnx.qcc.inputType.compiler.1443568066" superClass="com.qnx.qcc.inputType.compiler"/> + </tool> + <tool id="com.qnx.qcc.tool.assembler.1996828008" name="QCC Assembler" superClass="com.qnx.qcc.tool.assembler"> + <inputType id="com.qnx.qcc.inputType.assembler.116798417" superClass="com.qnx.qcc.inputType.assembler"/> + </tool> + <tool id="com.qnx.qcc.tool.linker.871546588" name="QCC Linker" superClass="com.qnx.qcc.tool.linker"> + <option id="com.qnx.qcc.option.linker.shared.915102752" name="Shared (-shared)" superClass="com.qnx.qcc.option.linker.shared" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.linker.libraryPaths.1049529253" name="Library Paths (-L)" superClass="com.qnx.qcc.option.linker.libraryPaths" valueType="libPaths"> + <listOptionValue builtIn="false" value="${QNX_TARGET}/../target-override/${CPUVARDIR}/lib"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/${CPUVARDIR}/usr/lib"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/${CPUVARDIR}/usr/lib/qt4/lib"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/../target-override/${CPUVARDIR}/usr/lib"/> + </option> + <option id="com.qnx.qcc.option.linker.security.1157664997" name="Enhanced Security (-Wl,-z,relro -Wl,-z,now)" superClass="com.qnx.qcc.option.linker.security" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.linker.libraries.1316432206" name="Libraries (-l)" superClass="com.qnx.qcc.option.linker.libraries" valueType="libs"> + <listOptionValue builtIn="false" value="slog2"/> + <listOptionValue builtIn="false" value="QtCore"/> + <listOptionValue builtIn="false" value="bb"/> + <listOptionValue builtIn="false" value="bps"/> + </option> + <inputType id="com.qnx.qcc.inputType.linker.1028572887" superClass="com.qnx.qcc.inputType.linker"> + <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> + <additionalInput kind="additionalinput" paths="$(LIBS)"/> + </inputType> + </tool> + <tool id="com.qnx.qcc.tool.archiver.1781914947" name="QCC Archiver" superClass="com.qnx.qcc.tool.archiver"/> + </toolChain> + </folderInfo> + <sourceEntries> + <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/> + <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="public"/> + </sourceEntries> + </configuration> + </storageModule> + <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> + </cconfiguration> + <cconfiguration id="com.qnx.qcc.configuration.sharedLib.debug.193597202.362186091"> + <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="com.qnx.qcc.configuration.sharedLib.debug.193597202.362186091" moduleId="org.eclipse.cdt.core.settings" name="simulator"> + <externalSettings> + <externalSetting> + <entry flags="VALUE_WORKSPACE_PATH" kind="includePath" name="/Cordova-Keyboard"/> + <entry flags="VALUE_WORKSPACE_PATH" kind="libraryPath" name="/Cordova-Keyboard/simulator"/> + <entry flags="RESOLVED" kind="libraryFile" name="Cordova-Keyboard" srcPrefixMapping="" srcRootPath=""/> + </externalSetting> + </externalSettings> + <extensions> + <extension id="com.qnx.tools.ide.qde.core.QDELinkerErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="com.qnx.tools.ide.qde.core.QDEBynaryParser" point="org.eclipse.cdt.core.BinaryParser"/> + </extensions> + </storageModule> + <storageModule moduleId="cdtBuildSystem" version="4.0.0"> + <configuration artifactExtension="so" artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.sharedLib" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.sharedLib" description="" id="com.qnx.qcc.configuration.sharedLib.debug.193597202.362186091" name="simulator" parent="com.qnx.qcc.configuration.sharedLib.debug"> + <folderInfo id="com.qnx.qcc.configuration.sharedLib.debug.193597202.362186091." name="/" resourcePath=""> + <toolChain id="com.qnx.qcc.toolChain.688026907" name="QNX QCC" superClass="com.qnx.qcc.toolChain"> + <targetPlatform archList="all" binaryParser="com.qnx.tools.ide.qde.core.QDEBynaryParser" id="com.qnx.qcc.targetPlatform.469207190" osList="all" superClass="com.qnx.qcc.targetPlatform"/> + <builder buildPath="${workspace_loc:/Keyboard/Simulator-Debug}" id="com.qnx.nto.2029800497" keepEnvironmentInBuildfile="false" name="CDT Internal Builder" superClass="com.qnx.nto"/> + <tool id="com.qnx.qcc.tool.compiler.1028279123" name="QCC Compiler" superClass="com.qnx.qcc.tool.compiler"> + <option id="com.qnx.qcc.option.compiler.shared.235893159" name="Shared (-shared)" superClass="com.qnx.qcc.option.compiler.shared" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.compiler.optlevel.1164238904" name="Optimization Level" superClass="com.qnx.qcc.option.compiler.optlevel" value="com.qnx.qcc.option.compiler.optlevel.0" valueType="enumerated"/> + <option id="com.qnx.qcc.option.compile.debug.3716470" name="Debug (-g)" superClass="com.qnx.qcc.option.compile.debug" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.compiler.includePath.306305432" name="Include Directories (-I)" superClass="com.qnx.qcc.option.compiler.includePath" valueType="includePath"> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/bb"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/qt4/QtCore"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/qt4"/> + <listOptionValue builtIn="false" value="${workspace_loc:/${ProjName}/public}"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/usr/include/freetype2"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/../target-override/usr/include"/> + </option> + <option id="com.qnx.qcc.option.compiler.security.1730007887" name="Enhanced Security (-fstack-protector-strong)" superClass="com.qnx.qcc.option.compiler.security" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.compiler.defines.1526896965" name="Defines (-D)" superClass="com.qnx.qcc.option.compiler.defines" valueType="definedSymbols"> + <listOptionValue builtIn="false" value="_FORTIFY_SOURCE=2"/> + </option> + <inputType id="com.qnx.qcc.inputType.compiler.1881183122" superClass="com.qnx.qcc.inputType.compiler"/> + </tool> + <tool id="com.qnx.qcc.tool.assembler.312168125" name="QCC Assembler" superClass="com.qnx.qcc.tool.assembler"> + <option id="com.qnx.qcc.option.assembler.debug.416544277" name="Debug (-g)" superClass="com.qnx.qcc.option.assembler.debug" value="true" valueType="boolean"/> + <inputType id="com.qnx.qcc.inputType.assembler.1722778407" superClass="com.qnx.qcc.inputType.assembler"/> + </tool> + <tool id="com.qnx.qcc.tool.linker.2130364088" name="QCC Linker" superClass="com.qnx.qcc.tool.linker"> + <option id="com.qnx.qcc.option.linker.debug.1332880614" name="Debug (-g)" superClass="com.qnx.qcc.option.linker.debug" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.linker.shared.1633267255" name="Shared (-shared)" superClass="com.qnx.qcc.option.linker.shared" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.linker.libraryPaths.565794953" name="Library Paths (-L)" superClass="com.qnx.qcc.option.linker.libraryPaths" valueType="libPaths"> + <listOptionValue builtIn="false" value="${QNX_TARGET}/../target-override/${CPUVARDIR}/lib"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/${CPUVARDIR}/usr/lib"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/${CPUVARDIR}/usr/lib/qt4/lib"/> + <listOptionValue builtIn="false" value="${QNX_TARGET}/../target-override/${CPUVARDIR}/usr/lib"/> + </option> + <option id="com.qnx.qcc.option.linker.security.9141791" name="Enhanced Security (-Wl,-z,relro -Wl,-z,now)" superClass="com.qnx.qcc.option.linker.security" value="true" valueType="boolean"/> + <option id="com.qnx.qcc.option.linker.libraries.220836649" name="Libraries (-l)" superClass="com.qnx.qcc.option.linker.libraries" valueType="libs"> + <listOptionValue builtIn="false" value="slog2"/> + <listOptionValue builtIn="false" value="QtCore"/> + <listOptionValue builtIn="false" value="bb"/> + <listOptionValue builtIn="false" value="bps"/> + </option> + <inputType id="com.qnx.qcc.inputType.linker.167117375" superClass="com.qnx.qcc.inputType.linker"> + <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> + <additionalInput kind="additionalinput" paths="$(LIBS)"/> + </inputType> + </tool> + <tool id="com.qnx.qcc.tool.archiver.489682882" name="QCC Archiver" superClass="com.qnx.qcc.tool.archiver"/> + </toolChain> + </folderInfo> + <sourceEntries> + <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/> + <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="public"/> + </sourceEntries> + </configuration> + </storageModule> + <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> + </cconfiguration> + </storageModule> + <storageModule moduleId="cdtBuildSystem" version="4.0.0"> + <project id="Keyboard.null.138005006" name="Keyboard"/> + </storageModule> + <storageModule moduleId="refreshScope" versionNumber="2"> + <configuration configurationName="Simulator-Profile"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="simulator"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="Simulator-Coverage"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="Device-Profile"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="Device-Debug"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="Simulator-Debug"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="device"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="Device-Release"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + <configuration configurationName="Device-Coverage"> + <resource resourceType="PROJECT" workspacePath="/Keyboard"/> + </configuration> + </storageModule> + <storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/> + <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/> + <storageModule moduleId="scannerConfiguration"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.profile.941124085"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.coverage.1806890017"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.release.608922875"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.profile.27502649"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.debug.193597202"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.coverage.537092296"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.debug.193597202.362186091"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.release.608922875.1009704567"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="com.qnx.qcc.configuration.sharedLib.debug.1877214659"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.qnx.tools.ide.qde.managedbuilder.core.qccScannerInfo"/> + </scannerConfigBuildInfo> + </storageModule> +</cproject> diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/.project b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/.project new file mode 100644 index 00000000..8a39f221 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/.project @@ -0,0 +1,76 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>Keyboard</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name> + <triggers>clean,full,incremental,</triggers> + <arguments> + <dictionary> + <key>?name?</key> + <value></value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.append_environment</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.buildArguments</key> + <value></value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.buildCommand</key> + <value>make</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.buildLocation</key> + <value>${workspace_loc:/Keyboard/Device-Release}</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.contents</key> + <value>org.eclipse.cdt.make.core.activeConfigSettings</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.enableAutoBuild</key> + <value>false</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.enableCleanBuild</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.enableFullBuild</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.stopOnError</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key> + <value>true</value> + </dictionary> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name> + <triggers>full,incremental,</triggers> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>com.qnx.tools.bbt.xml.core.bbtXMLValidationBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.cdt.core.cnature</nature> + <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature> + <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature> + <nature>com.qnx.tools.ide.bbt.core.bbtnature</nature> + </natures> +</projectDescription> diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/autolink.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/autolink.h new file mode 100644 index 00000000..37c9258e --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/autolink.h @@ -0,0 +1,19 @@ +#ifndef JSON_AUTOLINK_H_INCLUDED +# define JSON_AUTOLINK_H_INCLUDED + +# include "config.h" + +# ifdef JSON_IN_CPPTL +# include <cpptl/cpptl_autolink.h> +# endif + +# if !defined(JSON_NO_AUTOLINK) && !defined(JSON_DLL_BUILD) && !defined(JSON_IN_CPPTL) +# define CPPTL_AUTOLINK_NAME "json" +# undef CPPTL_AUTOLINK_DLL +# ifdef JSON_DLL +# define CPPTL_AUTOLINK_DLL +# endif +# include "autolink.h" +# endif + +#endif // JSON_AUTOLINK_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/config.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/config.h new file mode 100644 index 00000000..5d334cbc --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/config.h @@ -0,0 +1,43 @@ +#ifndef JSON_CONFIG_H_INCLUDED +# define JSON_CONFIG_H_INCLUDED + +/// If defined, indicates that json library is embedded in CppTL library. +//# define JSON_IN_CPPTL 1 + +/// If defined, indicates that json may leverage CppTL library +//# define JSON_USE_CPPTL 1 +/// If defined, indicates that cpptl vector based map should be used instead of std::map +/// as Value container. +//# define JSON_USE_CPPTL_SMALLMAP 1 +/// If defined, indicates that Json specific container should be used +/// (hash table & simple deque container with customizable allocator). +/// THIS FEATURE IS STILL EXPERIMENTAL! +//# define JSON_VALUE_USE_INTERNAL_MAP 1 +/// Force usage of standard new/malloc based allocator instead of memory pool based allocator. +/// The memory pools allocator used optimization (initializing Value and ValueInternalLink +/// as if it was a POD) that may cause some validation tool to report errors. +/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined. +//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1 + +/// If defined, indicates that Json use exception to report invalid type manipulation +/// instead of C assert macro. +# define JSON_USE_EXCEPTION 1 + +# ifdef JSON_IN_CPPTL +# include <cpptl/config.h> +# ifndef JSON_USE_CPPTL +# define JSON_USE_CPPTL 1 +# endif +# endif + +# ifdef JSON_IN_CPPTL +# define JSON_API CPPTL_API +# elif defined(JSON_DLL_BUILD) +# define JSON_API __declspec(dllexport) +# elif defined(JSON_DLL) +# define JSON_API __declspec(dllimport) +# else +# define JSON_API +# endif + +#endif // JSON_CONFIG_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/features.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/features.h new file mode 100644 index 00000000..5a9adec1 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/features.h @@ -0,0 +1,42 @@ +#ifndef CPPTL_JSON_FEATURES_H_INCLUDED +# define CPPTL_JSON_FEATURES_H_INCLUDED + +# include "forwards.h" + +namespace Json { + + /** \brief Configuration passed to reader and writer. + * This configuration object can be used to force the Reader or Writer + * to behave in a standard conforming way. + */ + class JSON_API Features + { + public: + /** \brief A configuration that allows all features and assumes all strings are UTF-8. + * - C & C++ comments are allowed + * - Root object can be any JSON value + * - Assumes Value strings are encoded in UTF-8 + */ + static Features all(); + + /** \brief A configuration that is strictly compatible with the JSON specification. + * - Comments are forbidden. + * - Root object must be either an array or an object value. + * - Assumes Value strings are encoded in UTF-8 + */ + static Features strictMode(); + + /** \brief Initialize the configuration like JsonConfig::allFeatures; + */ + Features(); + + /// \c true if comments are allowed. Default: \c true. + bool allowComments_; + + /// \c true if root must be either an array or an object value. Default: \c false. + bool strictRoot_; + }; + +} // namespace Json + +#endif // CPPTL_JSON_FEATURES_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/forwards.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/forwards.h new file mode 100644 index 00000000..d0ce8300 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/forwards.h @@ -0,0 +1,39 @@ +#ifndef JSON_FORWARDS_H_INCLUDED +# define JSON_FORWARDS_H_INCLUDED + +# include "config.h" + +namespace Json { + + // writer.h + class FastWriter; + class StyledWriter; + + // reader.h + class Reader; + + // features.h + class Features; + + // value.h + typedef int Int; + typedef unsigned int UInt; + class StaticString; + class Path; + class PathArgument; + class Value; + class ValueIteratorBase; + class ValueIterator; + class ValueConstIterator; +#ifdef JSON_VALUE_USE_INTERNAL_MAP + class ValueAllocator; + class ValueMapAllocator; + class ValueInternalLink; + class ValueInternalArray; + class ValueInternalMap; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + +} // namespace Json + + +#endif // JSON_FORWARDS_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/json.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/json.h new file mode 100644 index 00000000..c71ed65a --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/json.h @@ -0,0 +1,10 @@ +#ifndef JSON_JSON_H_INCLUDED +# define JSON_JSON_H_INCLUDED + +# include "autolink.h" +# include "value.h" +# include "reader.h" +# include "writer.h" +# include "features.h" + +#endif // JSON_JSON_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/reader.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/reader.h new file mode 100644 index 00000000..ee1d6a24 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/reader.h @@ -0,0 +1,196 @@ +#ifndef CPPTL_JSON_READER_H_INCLUDED +# define CPPTL_JSON_READER_H_INCLUDED + +# include "features.h" +# include "value.h" +# include <deque> +# include <stack> +# include <string> +# include <iostream> + +namespace Json { + + /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value. + * + */ + class JSON_API Reader + { + public: + typedef char Char; + typedef const Char *Location; + + /** \brief Constructs a Reader allowing all features + * for parsing. + */ + Reader(); + + /** \brief Constructs a Reader allowing the specified feature set + * for parsing. + */ + Reader( const Features &features ); + + /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document. + * \param document UTF-8 encoded string containing the document to read. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const std::string &document, + Value &root, + bool collectComments = true ); + + /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document. + * \param document UTF-8 encoded string containing the document to read. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them back during + * serialization, \c false to discard comments. + * This parameter is ignored if Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an error occurred. + */ + bool parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments = true ); + + /// \brief Parse from input stream. + /// \see Json::operator>>(std::istream&, Json::Value&). + bool parse( std::istream &is, + Value &root, + bool collectComments = true ); + + /** \brief Returns a user friendly string that list errors in the parsed document. + * \return Formatted error message with the list of errors with their location in + * the parsed document. An empty string is returned if no error occurred + * during parsing. + */ + std::string getFormatedErrorMessages() const; + + private: + enum TokenType + { + tokenEndOfStream = 0, + tokenObjectBegin, + tokenObjectEnd, + tokenArrayBegin, + tokenArrayEnd, + tokenString, + tokenNumber, + tokenTrue, + tokenFalse, + tokenNull, + tokenArraySeparator, + tokenMemberSeparator, + tokenComment, + tokenError + }; + + class Token + { + public: + TokenType type_; + Location start_; + Location end_; + }; + + class ErrorInfo + { + public: + Token token_; + std::string message_; + Location extra_; + }; + + typedef std::deque<ErrorInfo> Errors; + + bool expectToken( TokenType type, Token &token, const char *message ); + bool readToken( Token &token ); + void skipSpaces(); + bool match( Location pattern, + int patternLength ); + bool readComment(); + bool readCStyleComment(); + bool readCppStyleComment(); + bool readString(); + void readNumber(); + bool readValue(); + bool readObject( Token &token ); + bool readArray( Token &token ); + bool decodeNumber( Token &token ); + bool decodeString( Token &token ); + bool decodeString( Token &token, std::string &decoded ); + bool decodeDouble( Token &token ); + bool decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ); + bool addError( const std::string &message, + Token &token, + Location extra = 0 ); + bool recoverFromError( TokenType skipUntilToken ); + bool addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ); + void skipUntilSpace(); + Value ¤tValue(); + Char getNextChar(); + void getLocationLineAndColumn( Location location, + int &line, + int &column ) const; + std::string getLocationLineAndColumn( Location location ) const; + void addComment( Location begin, + Location end, + CommentPlacement placement ); + void skipCommentTokens( Token &token ); + + typedef std::stack<Value *> Nodes; + Nodes nodes_; + Errors errors_; + std::string document_; + Location begin_; + Location end_; + Location current_; + Location lastValueEnd_; + Value *lastValue_; + std::string commentsBefore_; + Features features_; + bool collectComments_; + }; + + /** \brief Read from 'sin' into 'root'. + + Always keep comments from the input JSON. + + This can be used to read a file into a particular sub-object. + For example: + \code + Json::Value root; + cin >> root["dir"]["file"]; + cout << root; + \endcode + Result: + \verbatim + { + "dir": { + "file": { + // The input stream JSON would be nested here. + } + } + } + \endverbatim + \throw std::exception on parse error. + \see Json::operator<<() + */ + std::istream& operator>>( std::istream&, Value& ); + +} // namespace Json + +#endif // CPPTL_JSON_READER_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/value.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/value.h new file mode 100644 index 00000000..58bfd88e --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/value.h @@ -0,0 +1,1069 @@ +#ifndef CPPTL_JSON_H_INCLUDED +# define CPPTL_JSON_H_INCLUDED + +# include "forwards.h" +# include <string> +# include <vector> + +# ifndef JSON_USE_CPPTL_SMALLMAP +# include <map> +# else +# include <cpptl/smallmap.h> +# endif +# ifdef JSON_USE_CPPTL +# include <cpptl/forwards.h> +# endif + +/** \brief JSON (JavaScript Object Notation). + */ +namespace Json { + + /** \brief Type of the value held by a Value object. + */ + enum ValueType + { + nullValue = 0, ///< 'null' value + intValue, ///< signed integer value + uintValue, ///< unsigned integer value + realValue, ///< double value + stringValue, ///< UTF-8 string value + booleanValue, ///< bool value + arrayValue, ///< array value (ordered list) + objectValue ///< object value (collection of name/value pairs). + }; + + enum CommentPlacement + { + commentBefore = 0, ///< a comment placed on the line before a value + commentAfterOnSameLine, ///< a comment just after a value on the same line + commentAfter, ///< a comment on the line after a value (only make sense for root value) + numberOfCommentPlacement + }; + +//# ifdef JSON_USE_CPPTL +// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames; +// typedef CppTL::AnyEnumerator<const Value &> EnumValues; +//# endif + + /** \brief Lightweight wrapper to tag static string. + * + * Value constructor and objectValue member assignement takes advantage of the + * StaticString and avoid the cost of string duplication when storing the + * string or the member name. + * + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + class JSON_API StaticString + { + public: + explicit StaticString( const char *czstring ) + : str_( czstring ) + { + } + + operator const char *() const + { + return str_; + } + + const char *c_str() const + { + return str_; + } + + private: + const char *str_; + }; + + /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value. + * + * This class is a discriminated union wrapper that can represents a: + * - signed integer [range: Value::minInt - Value::maxInt] + * - unsigned integer (range: 0 - Value::maxUInt) + * - double + * - UTF-8 string + * - boolean + * - 'null' + * - an ordered list of Value + * - collection of name/value pairs (javascript object) + * + * The type of the held value is represented by a #ValueType and + * can be obtained using type(). + * + * values of an #objectValue or #arrayValue can be accessed using operator[]() methods. + * Non const methods will automatically create the a #nullValue element + * if it does not exist. + * The sequence of an #arrayValue will be automatically resize and initialized + * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. + * + * The get() methods can be used to obtanis default value in the case the required element + * does not exist. + * + * It is possible to iterate over the list of a #objectValue values using + * the getMemberNames() method. + */ + class JSON_API Value + { + friend class ValueIteratorBase; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + friend class ValueInternalLink; + friend class ValueInternalMap; +# endif + public: + typedef std::vector<std::string> Members; + typedef ValueIterator iterator; + typedef ValueConstIterator const_iterator; + typedef Json::UInt UInt; + typedef Json::Int Int; + typedef UInt ArrayIndex; + + static const Value null; + static const Int minInt; + static const Int maxInt; + static const UInt maxUInt; + + private: +#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION +# ifndef JSON_VALUE_USE_INTERNAL_MAP + class CZString + { + public: + enum DuplicationPolicy + { + noDuplication = 0, + duplicate, + duplicateOnCopy + }; + CZString( int index ); + CZString( const char *cstr, DuplicationPolicy allocate ); + CZString( const CZString &other ); + ~CZString(); + CZString &operator =( const CZString &other ); + bool operator<( const CZString &other ) const; + bool operator==( const CZString &other ) const; + int index() const; + const char *c_str() const; + bool isStaticString() const; + private: + void swap( CZString &other ); + const char *cstr_; + int index_; + }; + + public: +# ifndef JSON_USE_CPPTL_SMALLMAP + typedef std::map<CZString, Value> ObjectValues; +# else + typedef CppTL::SmallMap<CZString, Value> ObjectValues; +# endif // ifndef JSON_USE_CPPTL_SMALLMAP +# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP +#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + public: + /** \brief Create a default Value of the given type. + + This is a very useful constructor. + To create an empty array, pass arrayValue. + To create an empty object, pass objectValue. + Another Value can then be set to this one by assignment. + This is useful since clear() and resize() will not alter types. + + Examples: + \code + Json::Value null_value; // null + Json::Value arr_value(Json::arrayValue); // [] + Json::Value obj_value(Json::objectValue); // {} + \endcode + */ + Value( ValueType type = nullValue ); + Value( Int value ); + Value( UInt value ); + Value( double value ); + Value( const char *value ); + Value( const char *beginValue, const char *endValue ); + /** \brief Constructs a value from a static string. + + * Like other value string constructor but do not duplicate the string for + * internal storage. The given string must remain alive after the call to this + * constructor. + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * \endcode + */ + Value( const StaticString &value ); + Value( const std::string &value ); +# ifdef JSON_USE_CPPTL + Value( const CppTL::ConstString &value ); +# endif + Value( bool value ); + Value( const Value &other ); + ~Value(); + + Value &operator=( const Value &other ); + /// Swap values. + /// \note Currently, comments are intentionally not swapped, for + /// both logic and efficiency. + void swap( Value &other ); + + ValueType type() const; + + bool operator <( const Value &other ) const; + bool operator <=( const Value &other ) const; + bool operator >=( const Value &other ) const; + bool operator >( const Value &other ) const; + + bool operator ==( const Value &other ) const; + bool operator !=( const Value &other ) const; + + int compare( const Value &other ); + + const char *asCString() const; + std::string asString() const; +# ifdef JSON_USE_CPPTL + CppTL::ConstString asConstString() const; +# endif + Int asInt() const; + UInt asUInt() const; + double asDouble() const; + bool asBool() const; + + bool isNull() const; + bool isBool() const; + bool isInt() const; + bool isUInt() const; + bool isIntegral() const; + bool isDouble() const; + bool isNumeric() const; + bool isString() const; + bool isArray() const; + bool isObject() const; + + bool isConvertibleTo( ValueType other ) const; + + /// Number of values in array or object + UInt size() const; + + /// \brief Return true if empty array, empty object, or null; + /// otherwise, false. + bool empty() const; + + /// Return isNull() + bool operator!() const; + + /// Remove all object members and array elements. + /// \pre type() is arrayValue, objectValue, or nullValue + /// \post type() is unchanged + void clear(); + + /// Resize the array to size elements. + /// New elements are initialized to null. + /// May only be called on nullValue or arrayValue. + /// \pre type() is arrayValue or nullValue + /// \post type() is arrayValue + void resize( UInt size ); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value &operator[]( UInt index ); + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value &operator[]( UInt index ) const; + /// If the array contains at least index+1 elements, returns the element value, + /// otherwise returns defaultValue. + Value get( UInt index, + const Value &defaultValue ) const; + /// Return true if index < size(). + bool isValidIndex( UInt index ) const; + /// \brief Append value to array at the end. + /// + /// Equivalent to jsonvalue[jsonvalue.size()] = value; + Value &append( const Value &value ); + + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const char *key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const char *key ) const; + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const std::string &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const std::string &key ) const; + /** \brief Access an object value by name, create a null member if it does not exist. + + * If the object as no entry for that name, then the member name used to store + * the new entry is not duplicated. + * Example of use: + * \code + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + Value &operator[]( const StaticString &key ); +# ifdef JSON_USE_CPPTL + /// Access an object value by name, create a null member if it does not exist. + Value &operator[]( const CppTL::ConstString &key ); + /// Access an object value by name, returns null if there is no member with that name. + const Value &operator[]( const CppTL::ConstString &key ) const; +# endif + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const char *key, + const Value &defaultValue ) const; + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const std::string &key, + const Value &defaultValue ) const; +# ifdef JSON_USE_CPPTL + /// Return the member named key if it exist, defaultValue otherwise. + Value get( const CppTL::ConstString &key, + const Value &defaultValue ) const; +# endif + /// \brief Remove and return the named member. + /// + /// Do nothing if it did not exist. + /// \return the removed Value, or null. + /// \pre type() is objectValue or nullValue + /// \post type() is unchanged + Value removeMember( const char* key ); + /// Same as removeMember(const char*) + Value removeMember( const std::string &key ); + + /// Return true if the object has a member named key. + bool isMember( const char *key ) const; + /// Return true if the object has a member named key. + bool isMember( const std::string &key ) const; +# ifdef JSON_USE_CPPTL + /// Return true if the object has a member named key. + bool isMember( const CppTL::ConstString &key ) const; +# endif + + /// \brief Return a list of the member names. + /// + /// If null, return an empty list. + /// \pre type() is objectValue or nullValue + /// \post if type() was nullValue, it remains nullValue + Members getMemberNames() const; + +//# ifdef JSON_USE_CPPTL +// EnumMemberNames enumMemberNames() const; +// EnumValues enumValues() const; +//# endif + + /// Comments must be //... or /* ... */ + void setComment( const char *comment, + CommentPlacement placement ); + /// Comments must be //... or /* ... */ + void setComment( const std::string &comment, + CommentPlacement placement ); + bool hasComment( CommentPlacement placement ) const; + /// Include delimiters and embedded newlines. + std::string getComment( CommentPlacement placement ) const; + + std::string toStyledString() const; + + const_iterator begin() const; + const_iterator end() const; + + iterator begin(); + iterator end(); + + private: + Value &resolveReference( const char *key, + bool isStatic ); + +# ifdef JSON_VALUE_USE_INTERNAL_MAP + inline bool isItemAvailable() const + { + return itemIsUsed_ == 0; + } + + inline void setItemUsed( bool isUsed = true ) + { + itemIsUsed_ = isUsed ? 1 : 0; + } + + inline bool isMemberNameStatic() const + { + return memberNameIsStatic_ == 0; + } + + inline void setMemberNameIsStatic( bool isStatic ) + { + memberNameIsStatic_ = isStatic ? 1 : 0; + } +# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP + + private: + struct CommentInfo + { + CommentInfo(); + ~CommentInfo(); + + void setComment( const char *text ); + + char *comment_; + }; + + //struct MemberNamesTransform + //{ + // typedef const char *result_type; + // const char *operator()( const CZString &name ) const + // { + // return name.c_str(); + // } + //}; + + union ValueHolder + { + Int int_; + UInt uint_; + double real_; + bool bool_; + char *string_; +# ifdef JSON_VALUE_USE_INTERNAL_MAP + ValueInternalArray *array_; + ValueInternalMap *map_; +#else + ObjectValues *map_; +# endif + } value_; + ValueType type_ : 8; + int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. +# ifdef JSON_VALUE_USE_INTERNAL_MAP + unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container. + int memberNameIsStatic_ : 1; // used by the ValueInternalMap container. +# endif + CommentInfo *comments_; + }; + + + /** \brief Experimental and untested: represents an element of the "path" to access a node. + */ + class PathArgument + { + public: + friend class Path; + + PathArgument(); + PathArgument( UInt index ); + PathArgument( const char *key ); + PathArgument( const std::string &key ); + + private: + enum Kind + { + kindNone = 0, + kindIndex, + kindKey + }; + std::string key_; + UInt index_; + Kind kind_; + }; + + /** \brief Experimental and untested: represents a "path" to access a node. + * + * Syntax: + * - "." => root node + * - ".[n]" => elements at index 'n' of root node (an array value) + * - ".name" => member named 'name' of root node (an object value) + * - ".name1.name2.name3" + * - ".[0][1][2].name1[3]" + * - ".%" => member name is provided as parameter + * - ".[%]" => index is provied as parameter + */ + class Path + { + public: + Path( const std::string &path, + const PathArgument &a1 = PathArgument(), + const PathArgument &a2 = PathArgument(), + const PathArgument &a3 = PathArgument(), + const PathArgument &a4 = PathArgument(), + const PathArgument &a5 = PathArgument() ); + + const Value &resolve( const Value &root ) const; + Value resolve( const Value &root, + const Value &defaultValue ) const; + /// Creates the "path" to access the specified node and returns a reference on the node. + Value &make( Value &root ) const; + + private: + typedef std::vector<const PathArgument *> InArgs; + typedef std::vector<PathArgument> Args; + + void makePath( const std::string &path, + const InArgs &in ); + void addPathInArg( const std::string &path, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ); + void invalidPath( const std::string &path, + int location ); + + Args args_; + }; + + /** \brief Experimental do not use: Allocator to customize member name and string value memory management done by Value. + * + * - makeMemberName() and releaseMemberName() are called to respectively duplicate and + * free an Json::objectValue member name. + * - duplicateStringValue() and releaseStringValue() are called similarly to + * duplicate and free a Json::stringValue value. + */ + class ValueAllocator + { + public: + enum { unknown = (unsigned)-1 }; + + virtual ~ValueAllocator(); + + virtual char *makeMemberName( const char *memberName ) = 0; + virtual void releaseMemberName( char *memberName ) = 0; + virtual char *duplicateStringValue( const char *value, + unsigned int length = unknown ) = 0; + virtual void releaseStringValue( char *value ) = 0; + }; + +#ifdef JSON_VALUE_USE_INTERNAL_MAP + /** \brief Allocator to customize Value internal map. + * Below is an example of a simple implementation (default implementation actually + * use memory pool for speed). + * \code + class DefaultValueMapAllocator : public ValueMapAllocator + { + public: // overridden from ValueMapAllocator + virtual ValueInternalMap *newMap() + { + return new ValueInternalMap(); + } + + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) + { + return new ValueInternalMap( other ); + } + + virtual void destructMap( ValueInternalMap *map ) + { + delete map; + } + + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) + { + return new ValueInternalLink[size]; + } + + virtual void releaseMapBuckets( ValueInternalLink *links ) + { + delete [] links; + } + + virtual ValueInternalLink *allocateMapLink() + { + return new ValueInternalLink(); + } + + virtual void releaseMapLink( ValueInternalLink *link ) + { + delete link; + } + }; + * \endcode + */ + class JSON_API ValueMapAllocator + { + public: + virtual ~ValueMapAllocator(); + virtual ValueInternalMap *newMap() = 0; + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0; + virtual void destructMap( ValueInternalMap *map ) = 0; + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0; + virtual void releaseMapBuckets( ValueInternalLink *links ) = 0; + virtual ValueInternalLink *allocateMapLink() = 0; + virtual void releaseMapLink( ValueInternalLink *link ) = 0; + }; + + /** \brief ValueInternalMap hash-map bucket chain link (for internal use only). + * \internal previous_ & next_ allows for bidirectional traversal. + */ + class JSON_API ValueInternalLink + { + public: + enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture. + enum InternalFlags { + flagAvailable = 0, + flagUsed = 1 + }; + + ValueInternalLink(); + + ~ValueInternalLink(); + + Value items_[itemPerLink]; + char *keys_[itemPerLink]; + ValueInternalLink *previous_; + ValueInternalLink *next_; + }; + + + /** \brief A linked page based hash-table implementation used internally by Value. + * \internal ValueInternalMap is a tradional bucket based hash-table, with a linked + * list in each bucket to handle collision. There is an addional twist in that + * each node of the collision linked list is a page containing a fixed amount of + * value. This provides a better compromise between memory usage and speed. + * + * Each bucket is made up of a chained list of ValueInternalLink. The last + * link of a given bucket can be found in the 'previous_' field of the following bucket. + * The last link of the last bucket is stored in tailLink_ as it has no following bucket. + * Only the last link of a bucket may contains 'available' item. The last link always + * contains at least one element unless is it the bucket one very first link. + */ + class JSON_API ValueInternalMap + { + friend class ValueIteratorBase; + friend class Value; + public: + typedef unsigned int HashKey; + typedef unsigned int BucketIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState + { + IteratorState() + : map_(0) + , link_(0) + , itemIndex_(0) + , bucketIndex_(0) + { + } + ValueInternalMap *map_; + ValueInternalLink *link_; + BucketIndex itemIndex_; + BucketIndex bucketIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalMap(); + ValueInternalMap( const ValueInternalMap &other ); + ValueInternalMap &operator =( const ValueInternalMap &other ); + ~ValueInternalMap(); + + void swap( ValueInternalMap &other ); + + BucketIndex size() const; + + void clear(); + + bool reserveDelta( BucketIndex growth ); + + bool reserve( BucketIndex newItemCount ); + + const Value *find( const char *key ) const; + + Value *find( const char *key ); + + Value &resolveReference( const char *key, + bool isStatic ); + + void remove( const char *key ); + + void doActualRemove( ValueInternalLink *link, + BucketIndex index, + BucketIndex bucketIndex ); + + ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex ); + + Value &setNewItem( const char *key, + bool isStatic, + ValueInternalLink *link, + BucketIndex index ); + + Value &unsafeAdd( const char *key, + bool isStatic, + HashKey hashedKey ); + + HashKey hash( const char *key ) const; + + int compare( const ValueInternalMap &other ) const; + + private: + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void incrementBucket( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static const char *key( const IteratorState &iterator ); + static const char *key( const IteratorState &iterator, bool &isStatic ); + static Value &value( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + + private: + ValueInternalLink *buckets_; + ValueInternalLink *tailLink_; + BucketIndex bucketsSize_; + BucketIndex itemCount_; + }; + + /** \brief A simplified deque implementation used internally by Value. + * \internal + * It is based on a list of fixed "page", each page contains a fixed number of items. + * Instead of using a linked-list, a array of pointer is used for fast item look-up. + * Look-up for an element is as follow: + * - compute page index: pageIndex = itemIndex / itemsPerPage + * - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage] + * + * Insertion is amortized constant time (only the array containing the index of pointers + * need to be reallocated when items are appended). + */ + class JSON_API ValueInternalArray + { + friend class Value; + friend class ValueIteratorBase; + public: + enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo. + typedef Value::ArrayIndex ArrayIndex; + typedef unsigned int PageIndex; + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + struct IteratorState // Must be a POD + { + IteratorState() + : array_(0) + , currentPageIndex_(0) + , currentItemIndex_(0) + { + } + ValueInternalArray *array_; + Value **currentPageIndex_; + unsigned int currentItemIndex_; + }; +# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + + ValueInternalArray(); + ValueInternalArray( const ValueInternalArray &other ); + ValueInternalArray &operator =( const ValueInternalArray &other ); + ~ValueInternalArray(); + void swap( ValueInternalArray &other ); + + void clear(); + void resize( ArrayIndex newSize ); + + Value &resolveReference( ArrayIndex index ); + + Value *find( ArrayIndex index ) const; + + ArrayIndex size() const; + + int compare( const ValueInternalArray &other ) const; + + private: + static bool equals( const IteratorState &x, const IteratorState &other ); + static void increment( IteratorState &iterator ); + static void decrement( IteratorState &iterator ); + static Value &dereference( const IteratorState &iterator ); + static Value &unsafeDereference( const IteratorState &iterator ); + static int distance( const IteratorState &x, const IteratorState &y ); + static ArrayIndex indexOf( const IteratorState &iterator ); + void makeBeginIterator( IteratorState &it ) const; + void makeEndIterator( IteratorState &it ) const; + void makeIterator( IteratorState &it, ArrayIndex index ) const; + + void makeIndexValid( ArrayIndex index ); + + Value **pages_; + ArrayIndex size_; + PageIndex pageCount_; + }; + + /** \brief Experimental: do not use. Allocator to customize Value internal array. + * Below is an example of a simple implementation (actual implementation use + * memory pool). + \code +class DefaultValueArrayAllocator : public ValueArrayAllocator +{ +public: // overridden from ValueArrayAllocator + virtual ~DefaultValueArrayAllocator() + { + } + + virtual ValueInternalArray *newArray() + { + return new ValueInternalArray(); + } + + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) + { + return new ValueInternalArray( other ); + } + + virtual void destruct( ValueInternalArray *array ) + { + delete array; + } + + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) + { + ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; + if ( minNewIndexCount > newIndexCount ) + newIndexCount = minNewIndexCount; + void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); + if ( !newIndexes ) + throw std::bad_alloc(); + indexCount = newIndexCount; + indexes = static_cast<Value **>( newIndexes ); + } + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) + { + if ( indexes ) + free( indexes ); + } + + virtual Value *allocateArrayPage() + { + return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) ); + } + + virtual void releaseArrayPage( Value *value ) + { + if ( value ) + free( value ); + } +}; + \endcode + */ + class JSON_API ValueArrayAllocator + { + public: + virtual ~ValueArrayAllocator(); + virtual ValueInternalArray *newArray() = 0; + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0; + virtual void destructArray( ValueInternalArray *array ) = 0; + /** \brief Reallocate array page index. + * Reallocates an array of pointer on each page. + * \param indexes [input] pointer on the current index. May be \c NULL. + * [output] pointer on the new index of at least + * \a minNewIndexCount pages. + * \param indexCount [input] current number of pages in the index. + * [output] number of page the reallocated index can handle. + * \b MUST be >= \a minNewIndexCount. + * \param minNewIndexCount Minimum number of page the new index must be able to + * handle. + */ + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) = 0; + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) = 0; + virtual Value *allocateArrayPage() = 0; + virtual void releaseArrayPage( Value *value ) = 0; + }; +#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP + + + /** \brief base class for Value iterators. + * + */ + class ValueIteratorBase + { + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef ValueIteratorBase SelfType; + + ValueIteratorBase(); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIteratorBase( const Value::ObjectValues::iterator ¤t ); +#else + ValueIteratorBase( const ValueInternalArray::IteratorState &state ); + ValueIteratorBase( const ValueInternalMap::IteratorState &state ); +#endif + + bool operator ==( const SelfType &other ) const + { + return isEqual( other ); + } + + bool operator !=( const SelfType &other ) const + { + return !isEqual( other ); + } + + difference_type operator -( const SelfType &other ) const + { + return computeDistance( other ); + } + + /// Return either the index or the member name of the referenced value as a Value. + Value key() const; + + /// Return the index of the referenced Value. -1 if it is not an arrayValue. + UInt index() const; + + /// Return the member name of the referenced Value. "" if it is not an objectValue. + const char *memberName() const; + + protected: + Value &deref() const; + + void increment(); + + void decrement(); + + difference_type computeDistance( const SelfType &other ) const; + + bool isEqual( const SelfType &other ) const; + + void copy( const SelfType &other ); + + private: +#ifndef JSON_VALUE_USE_INTERNAL_MAP + Value::ObjectValues::iterator current_; + // Indicates that iterator is for a null value. + bool isNull_; +#else + union + { + ValueInternalArray::IteratorState array_; + ValueInternalMap::IteratorState map_; + } iterator_; + bool isArray_; +#endif + }; + + /** \brief const iterator for object and array value. + * + */ + class ValueConstIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef const Value &reference; + typedef const Value *pointer; + typedef ValueConstIterator SelfType; + + ValueConstIterator(); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueConstIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueConstIterator( const ValueInternalArray::IteratorState &state ); + ValueConstIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + SelfType &operator =( const ValueIteratorBase &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + + /** \brief Iterator for object and array value. + */ + class ValueIterator : public ValueIteratorBase + { + friend class Value; + public: + typedef unsigned int size_t; + typedef int difference_type; + typedef Value &reference; + typedef Value *pointer; + typedef ValueIterator SelfType; + + ValueIterator(); + ValueIterator( const ValueConstIterator &other ); + ValueIterator( const ValueIterator &other ); + private: + /*! \internal Use by Value to create an iterator. + */ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + explicit ValueIterator( const Value::ObjectValues::iterator ¤t ); +#else + ValueIterator( const ValueInternalArray::IteratorState &state ); + ValueIterator( const ValueInternalMap::IteratorState &state ); +#endif + public: + + SelfType &operator =( const SelfType &other ); + + SelfType operator++( int ) + { + SelfType temp( *this ); + ++*this; + return temp; + } + + SelfType operator--( int ) + { + SelfType temp( *this ); + --*this; + return temp; + } + + SelfType &operator--() + { + decrement(); + return *this; + } + + SelfType &operator++() + { + increment(); + return *this; + } + + reference operator *() const + { + return deref(); + } + }; + + +} // namespace Json + + +#endif // CPPTL_JSON_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/writer.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/writer.h new file mode 100644 index 00000000..5f4b83be --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json/writer.h @@ -0,0 +1,174 @@ +#ifndef JSON_WRITER_H_INCLUDED +# define JSON_WRITER_H_INCLUDED + +# include "value.h" +# include <vector> +# include <string> +# include <iostream> + +namespace Json { + + class Value; + + /** \brief Abstract class for writers. + */ + class JSON_API Writer + { + public: + virtual ~Writer(); + + virtual std::string write( const Value &root ) = 0; + }; + + /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format without formatting (not human friendly). + * + * The JSON document is written in a single line. It is not intended for 'human' consumption, + * but may be usefull to support feature such as RPC where bandwith is limited. + * \sa Reader, Value + */ + class JSON_API FastWriter : public Writer + { + public: + FastWriter(); + virtual ~FastWriter(){} + + void enableYAMLCompatibility(); + + public: // overridden from Writer + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + + std::string document_; + bool yamlCompatiblityEnabled_; + }; + + /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledWriter: public Writer + { + public: + StyledWriter(); + virtual ~StyledWriter(){} + + public: // overridden from Writer + /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format. + * \param root Value to serialize. + * \return String containing the JSON document that represents the root value. + */ + virtual std::string write( const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector<std::string> ChildValues; + + ChildValues childValues_; + std::string document_; + std::string indentString_; + int rightMargin_; + int indentSize_; + bool addChildValues_; + }; + + /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way, + to a stream rather than to a string. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value types, + * and all the values fit on one lines, then print the array on a single line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputed according to their #CommentPlacement. + * + * \param indentation Each level will be indented by this amount extra. + * \sa Reader, Value, Value::setComment() + */ + class JSON_API StyledStreamWriter + { + public: + StyledStreamWriter( std::string indentation="\t" ); + ~StyledStreamWriter(){} + + public: + /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format. + * \param out Stream to write to. (Can be ostringstream, e.g.) + * \param root Value to serialize. + * \note There is no point in deriving from Writer, since write() should not return a value. + */ + void write( std::ostream &out, const Value &root ); + + private: + void writeValue( const Value &value ); + void writeArrayValue( const Value &value ); + bool isMultineArray( const Value &value ); + void pushValue( const std::string &value ); + void writeIndent(); + void writeWithIndent( const std::string &value ); + void indent(); + void unindent(); + void writeCommentBeforeValue( const Value &root ); + void writeCommentAfterValueOnSameLine( const Value &root ); + bool hasCommentForValue( const Value &value ); + static std::string normalizeEOL( const std::string &text ); + + typedef std::vector<std::string> ChildValues; + + ChildValues childValues_; + std::ostream* document_; + std::string indentString_; + int rightMargin_; + std::string indentation_; + bool addChildValues_; + }; + + std::string JSON_API valueToString( Int value ); + std::string JSON_API valueToString( UInt value ); + std::string JSON_API valueToString( double value ); + std::string JSON_API valueToString( bool value ); + std::string JSON_API valueToQuotedString( const char *value ); + + /// \brief Output using the StyledStreamWriter. + /// \see Json::operator>>() + std::ostream& operator<<( std::ostream&, const Value &root ); + +} // namespace Json + + + +#endif // JSON_WRITER_H_INCLUDED diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_batchallocator.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_batchallocator.h new file mode 100644 index 00000000..87ea5ed8 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_batchallocator.h @@ -0,0 +1,125 @@ +#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED +# define JSONCPP_BATCHALLOCATOR_H_INCLUDED + +# include <stdlib.h> +# include <assert.h> + +# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + +namespace Json { + +/* Fast memory allocator. + * + * This memory allocator allocates memory for a batch of object (specified by + * the page size, the number of object in each page). + * + * It does not allow the destruction of a single object. All the allocated objects + * can be destroyed at once. The memory can be either released or reused for future + * allocation. + * + * The in-place new operator must be used to construct the object using the pointer + * returned by allocate. + */ +template<typename AllocatedType + ,const unsigned int objectPerAllocation> +class BatchAllocator +{ +public: + typedef AllocatedType Type; + + BatchAllocator( unsigned int objectsPerPage = 255 ) + : freeHead_( 0 ) + , objectsPerPage_( objectsPerPage ) + { +// printf( "Size: %d => %s\n", sizeof(AllocatedType), typeid(AllocatedType).name() ); + assert( sizeof(AllocatedType) * objectPerAllocation >= sizeof(AllocatedType *) ); // We must be able to store a slist in the object free space. + assert( objectsPerPage >= 16 ); + batches_ = allocateBatch( 0 ); // allocated a dummy page + currentBatch_ = batches_; + } + + ~BatchAllocator() + { + for ( BatchInfo *batch = batches_; batch; ) + { + BatchInfo *nextBatch = batch->next_; + free( batch ); + batch = nextBatch; + } + } + + /// allocate space for an array of objectPerAllocation object. + /// @warning it is the responsability of the caller to call objects constructors. + AllocatedType *allocate() + { + if ( freeHead_ ) // returns node from free list. + { + AllocatedType *object = freeHead_; + freeHead_ = *(AllocatedType **)object; + return object; + } + if ( currentBatch_->used_ == currentBatch_->end_ ) + { + currentBatch_ = currentBatch_->next_; + while ( currentBatch_ && currentBatch_->used_ == currentBatch_->end_ ) + currentBatch_ = currentBatch_->next_; + + if ( !currentBatch_ ) // no free batch found, allocate a new one + { + currentBatch_ = allocateBatch( objectsPerPage_ ); + currentBatch_->next_ = batches_; // insert at the head of the list + batches_ = currentBatch_; + } + } + AllocatedType *allocated = currentBatch_->used_; + currentBatch_->used_ += objectPerAllocation; + return allocated; + } + + /// Release the object. + /// @warning it is the responsability of the caller to actually destruct the object. + void release( AllocatedType *object ) + { + assert( object != 0 ); + *(AllocatedType **)object = freeHead_; + freeHead_ = object; + } + +private: + struct BatchInfo + { + BatchInfo *next_; + AllocatedType *used_; + AllocatedType *end_; + AllocatedType buffer_[objectPerAllocation]; + }; + + // disabled copy constructor and assignement operator. + BatchAllocator( const BatchAllocator & ); + void operator =( const BatchAllocator &); + + static BatchInfo *allocateBatch( unsigned int objectsPerPage ) + { + const unsigned int mallocSize = sizeof(BatchInfo) - sizeof(AllocatedType)* objectPerAllocation + + sizeof(AllocatedType) * objectPerAllocation * objectsPerPage; + BatchInfo *batch = static_cast<BatchInfo*>( malloc( mallocSize ) ); + batch->next_ = 0; + batch->used_ = batch->buffer_; + batch->end_ = batch->buffer_ + objectsPerPage; + return batch; + } + + BatchInfo *batches_; + BatchInfo *currentBatch_; + /// Head of a single linked list within the allocated space of freeed object + AllocatedType *freeHead_; + unsigned int objectsPerPage_; +}; + + +} // namespace Json + +# endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION + +#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_internalarray.inl b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_internalarray.inl new file mode 100644 index 00000000..9b985d25 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_internalarray.inl @@ -0,0 +1,448 @@ +// included by json_value.cpp +// everything is within Json namespace + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueInternalArray +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueArrayAllocator::~ValueArrayAllocator() +{ +} + +// ////////////////////////////////////////////////////////////////// +// class DefaultValueArrayAllocator +// ////////////////////////////////////////////////////////////////// +#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +class DefaultValueArrayAllocator : public ValueArrayAllocator +{ +public: // overridden from ValueArrayAllocator + virtual ~DefaultValueArrayAllocator() + { + } + + virtual ValueInternalArray *newArray() + { + return new ValueInternalArray(); + } + + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) + { + return new ValueInternalArray( other ); + } + + virtual void destructArray( ValueInternalArray *array ) + { + delete array; + } + + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) + { + ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; + if ( minNewIndexCount > newIndexCount ) + newIndexCount = minNewIndexCount; + void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); + if ( !newIndexes ) + throw std::bad_alloc(); + indexCount = newIndexCount; + indexes = static_cast<Value **>( newIndexes ); + } + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) + { + if ( indexes ) + free( indexes ); + } + + virtual Value *allocateArrayPage() + { + return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) ); + } + + virtual void releaseArrayPage( Value *value ) + { + if ( value ) + free( value ); + } +}; + +#else // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +/// @todo make this thread-safe (lock when accessign batch allocator) +class DefaultValueArrayAllocator : public ValueArrayAllocator +{ +public: // overridden from ValueArrayAllocator + virtual ~DefaultValueArrayAllocator() + { + } + + virtual ValueInternalArray *newArray() + { + ValueInternalArray *array = arraysAllocator_.allocate(); + new (array) ValueInternalArray(); // placement new + return array; + } + + virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) + { + ValueInternalArray *array = arraysAllocator_.allocate(); + new (array) ValueInternalArray( other ); // placement new + return array; + } + + virtual void destructArray( ValueInternalArray *array ) + { + if ( array ) + { + array->~ValueInternalArray(); + arraysAllocator_.release( array ); + } + } + + virtual void reallocateArrayPageIndex( Value **&indexes, + ValueInternalArray::PageIndex &indexCount, + ValueInternalArray::PageIndex minNewIndexCount ) + { + ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; + if ( minNewIndexCount > newIndexCount ) + newIndexCount = minNewIndexCount; + void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); + if ( !newIndexes ) + throw std::bad_alloc(); + indexCount = newIndexCount; + indexes = static_cast<Value **>( newIndexes ); + } + virtual void releaseArrayPageIndex( Value **indexes, + ValueInternalArray::PageIndex indexCount ) + { + if ( indexes ) + free( indexes ); + } + + virtual Value *allocateArrayPage() + { + return static_cast<Value *>( pagesAllocator_.allocate() ); + } + + virtual void releaseArrayPage( Value *value ) + { + if ( value ) + pagesAllocator_.release( value ); + } +private: + BatchAllocator<ValueInternalArray,1> arraysAllocator_; + BatchAllocator<Value,ValueInternalArray::itemsPerPage> pagesAllocator_; +}; +#endif // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR + +static ValueArrayAllocator *&arrayAllocator() +{ + static DefaultValueArrayAllocator defaultAllocator; + static ValueArrayAllocator *arrayAllocator = &defaultAllocator; + return arrayAllocator; +} + +static struct DummyArrayAllocatorInitializer { + DummyArrayAllocatorInitializer() + { + arrayAllocator(); // ensure arrayAllocator() statics are initialized before main(). + } +} dummyArrayAllocatorInitializer; + +// ////////////////////////////////////////////////////////////////// +// class ValueInternalArray +// ////////////////////////////////////////////////////////////////// +bool +ValueInternalArray::equals( const IteratorState &x, + const IteratorState &other ) +{ + return x.array_ == other.array_ + && x.currentItemIndex_ == other.currentItemIndex_ + && x.currentPageIndex_ == other.currentPageIndex_; +} + + +void +ValueInternalArray::increment( IteratorState &it ) +{ + JSON_ASSERT_MESSAGE( it.array_ && + (it.currentPageIndex_ - it.array_->pages_)*itemsPerPage + it.currentItemIndex_ + != it.array_->size_, + "ValueInternalArray::increment(): moving iterator beyond end" ); + ++(it.currentItemIndex_); + if ( it.currentItemIndex_ == itemsPerPage ) + { + it.currentItemIndex_ = 0; + ++(it.currentPageIndex_); + } +} + + +void +ValueInternalArray::decrement( IteratorState &it ) +{ + JSON_ASSERT_MESSAGE( it.array_ && it.currentPageIndex_ == it.array_->pages_ + && it.currentItemIndex_ == 0, + "ValueInternalArray::decrement(): moving iterator beyond end" ); + if ( it.currentItemIndex_ == 0 ) + { + it.currentItemIndex_ = itemsPerPage-1; + --(it.currentPageIndex_); + } + else + { + --(it.currentItemIndex_); + } +} + + +Value & +ValueInternalArray::unsafeDereference( const IteratorState &it ) +{ + return (*(it.currentPageIndex_))[it.currentItemIndex_]; +} + + +Value & +ValueInternalArray::dereference( const IteratorState &it ) +{ + JSON_ASSERT_MESSAGE( it.array_ && + (it.currentPageIndex_ - it.array_->pages_)*itemsPerPage + it.currentItemIndex_ + < it.array_->size_, + "ValueInternalArray::dereference(): dereferencing invalid iterator" ); + return unsafeDereference( it ); +} + +void +ValueInternalArray::makeBeginIterator( IteratorState &it ) const +{ + it.array_ = const_cast<ValueInternalArray *>( this ); + it.currentItemIndex_ = 0; + it.currentPageIndex_ = pages_; +} + + +void +ValueInternalArray::makeIterator( IteratorState &it, ArrayIndex index ) const +{ + it.array_ = const_cast<ValueInternalArray *>( this ); + it.currentItemIndex_ = index % itemsPerPage; + it.currentPageIndex_ = pages_ + index / itemsPerPage; +} + + +void +ValueInternalArray::makeEndIterator( IteratorState &it ) const +{ + makeIterator( it, size_ ); +} + + +ValueInternalArray::ValueInternalArray() + : pages_( 0 ) + , size_( 0 ) + , pageCount_( 0 ) +{ +} + + +ValueInternalArray::ValueInternalArray( const ValueInternalArray &other ) + : pages_( 0 ) + , pageCount_( 0 ) + , size_( other.size_ ) +{ + PageIndex minNewPages = other.size_ / itemsPerPage; + arrayAllocator()->reallocateArrayPageIndex( pages_, pageCount_, minNewPages ); + JSON_ASSERT_MESSAGE( pageCount_ >= minNewPages, + "ValueInternalArray::reserve(): bad reallocation" ); + IteratorState itOther; + other.makeBeginIterator( itOther ); + Value *value; + for ( ArrayIndex index = 0; index < size_; ++index, increment(itOther) ) + { + if ( index % itemsPerPage == 0 ) + { + PageIndex pageIndex = index / itemsPerPage; + value = arrayAllocator()->allocateArrayPage(); + pages_[pageIndex] = value; + } + new (value) Value( dereference( itOther ) ); + } +} + + +ValueInternalArray & +ValueInternalArray::operator =( const ValueInternalArray &other ) +{ + ValueInternalArray temp( other ); + swap( temp ); + return *this; +} + + +ValueInternalArray::~ValueInternalArray() +{ + // destroy all constructed items + IteratorState it; + IteratorState itEnd; + makeBeginIterator( it); + makeEndIterator( itEnd ); + for ( ; !equals(it,itEnd); increment(it) ) + { + Value *value = &dereference(it); + value->~Value(); + } + // release all pages + PageIndex lastPageIndex = size_ / itemsPerPage; + for ( PageIndex pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex ) + arrayAllocator()->releaseArrayPage( pages_[pageIndex] ); + // release pages index + arrayAllocator()->releaseArrayPageIndex( pages_, pageCount_ ); +} + + +void +ValueInternalArray::swap( ValueInternalArray &other ) +{ + Value **tempPages = pages_; + pages_ = other.pages_; + other.pages_ = tempPages; + ArrayIndex tempSize = size_; + size_ = other.size_; + other.size_ = tempSize; + PageIndex tempPageCount = pageCount_; + pageCount_ = other.pageCount_; + other.pageCount_ = tempPageCount; +} + +void +ValueInternalArray::clear() +{ + ValueInternalArray dummy; + swap( dummy ); +} + + +void +ValueInternalArray::resize( ArrayIndex newSize ) +{ + if ( newSize == 0 ) + clear(); + else if ( newSize < size_ ) + { + IteratorState it; + IteratorState itEnd; + makeIterator( it, newSize ); + makeIterator( itEnd, size_ ); + for ( ; !equals(it,itEnd); increment(it) ) + { + Value *value = &dereference(it); + value->~Value(); + } + PageIndex pageIndex = (newSize + itemsPerPage - 1) / itemsPerPage; + PageIndex lastPageIndex = size_ / itemsPerPage; + for ( ; pageIndex < lastPageIndex; ++pageIndex ) + arrayAllocator()->releaseArrayPage( pages_[pageIndex] ); + size_ = newSize; + } + else if ( newSize > size_ ) + resolveReference( newSize ); +} + + +void +ValueInternalArray::makeIndexValid( ArrayIndex index ) +{ + // Need to enlarge page index ? + if ( index >= pageCount_ * itemsPerPage ) + { + PageIndex minNewPages = (index + 1) / itemsPerPage; + arrayAllocator()->reallocateArrayPageIndex( pages_, pageCount_, minNewPages ); + JSON_ASSERT_MESSAGE( pageCount_ >= minNewPages, "ValueInternalArray::reserve(): bad reallocation" ); + } + + // Need to allocate new pages ? + ArrayIndex nextPageIndex = + (size_ % itemsPerPage) != 0 ? size_ - (size_%itemsPerPage) + itemsPerPage + : size_; + if ( nextPageIndex <= index ) + { + PageIndex pageIndex = nextPageIndex / itemsPerPage; + PageIndex pageToAllocate = (index - nextPageIndex) / itemsPerPage + 1; + for ( ; pageToAllocate-- > 0; ++pageIndex ) + pages_[pageIndex] = arrayAllocator()->allocateArrayPage(); + } + + // Initialize all new entries + IteratorState it; + IteratorState itEnd; + makeIterator( it, size_ ); + size_ = index + 1; + makeIterator( itEnd, size_ ); + for ( ; !equals(it,itEnd); increment(it) ) + { + Value *value = &dereference(it); + new (value) Value(); // Construct a default value using placement new + } +} + +Value & +ValueInternalArray::resolveReference( ArrayIndex index ) +{ + if ( index >= size_ ) + makeIndexValid( index ); + return pages_[index/itemsPerPage][index%itemsPerPage]; +} + +Value * +ValueInternalArray::find( ArrayIndex index ) const +{ + if ( index >= size_ ) + return 0; + return &(pages_[index/itemsPerPage][index%itemsPerPage]); +} + +ValueInternalArray::ArrayIndex +ValueInternalArray::size() const +{ + return size_; +} + +int +ValueInternalArray::distance( const IteratorState &x, const IteratorState &y ) +{ + return indexOf(y) - indexOf(x); +} + + +ValueInternalArray::ArrayIndex +ValueInternalArray::indexOf( const IteratorState &iterator ) +{ + if ( !iterator.array_ ) + return ArrayIndex(-1); + return ArrayIndex( + (iterator.currentPageIndex_ - iterator.array_->pages_) * itemsPerPage + + iterator.currentItemIndex_ ); +} + + +int +ValueInternalArray::compare( const ValueInternalArray &other ) const +{ + int sizeDiff( size_ - other.size_ ); + if ( sizeDiff != 0 ) + return sizeDiff; + + for ( ArrayIndex index =0; index < size_; ++index ) + { + int diff = pages_[index/itemsPerPage][index%itemsPerPage].compare( + other.pages_[index/itemsPerPage][index%itemsPerPage] ); + if ( diff != 0 ) + return diff; + } + return 0; +} diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_internalmap.inl b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_internalmap.inl new file mode 100644 index 00000000..19771488 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_internalmap.inl @@ -0,0 +1,607 @@ +// included by json_value.cpp +// everything is within Json namespace + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueInternalMap +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +/** \internal MUST be safely initialized using memset( this, 0, sizeof(ValueInternalLink) ); + * This optimization is used by the fast allocator. + */ +ValueInternalLink::ValueInternalLink() + : previous_( 0 ) + , next_( 0 ) +{ +} + +ValueInternalLink::~ValueInternalLink() +{ + for ( int index =0; index < itemPerLink; ++index ) + { + if ( !items_[index].isItemAvailable() ) + { + if ( !items_[index].isMemberNameStatic() ) + free( keys_[index] ); + } + else + break; + } +} + + + +ValueMapAllocator::~ValueMapAllocator() +{ +} + +#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +class DefaultValueMapAllocator : public ValueMapAllocator +{ +public: // overridden from ValueMapAllocator + virtual ValueInternalMap *newMap() + { + return new ValueInternalMap(); + } + + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) + { + return new ValueInternalMap( other ); + } + + virtual void destructMap( ValueInternalMap *map ) + { + delete map; + } + + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) + { + return new ValueInternalLink[size]; + } + + virtual void releaseMapBuckets( ValueInternalLink *links ) + { + delete [] links; + } + + virtual ValueInternalLink *allocateMapLink() + { + return new ValueInternalLink(); + } + + virtual void releaseMapLink( ValueInternalLink *link ) + { + delete link; + } +}; +#else +/// @todo make this thread-safe (lock when accessign batch allocator) +class DefaultValueMapAllocator : public ValueMapAllocator +{ +public: // overridden from ValueMapAllocator + virtual ValueInternalMap *newMap() + { + ValueInternalMap *map = mapsAllocator_.allocate(); + new (map) ValueInternalMap(); // placement new + return map; + } + + virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) + { + ValueInternalMap *map = mapsAllocator_.allocate(); + new (map) ValueInternalMap( other ); // placement new + return map; + } + + virtual void destructMap( ValueInternalMap *map ) + { + if ( map ) + { + map->~ValueInternalMap(); + mapsAllocator_.release( map ); + } + } + + virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) + { + return new ValueInternalLink[size]; + } + + virtual void releaseMapBuckets( ValueInternalLink *links ) + { + delete [] links; + } + + virtual ValueInternalLink *allocateMapLink() + { + ValueInternalLink *link = linksAllocator_.allocate(); + memset( link, 0, sizeof(ValueInternalLink) ); + return link; + } + + virtual void releaseMapLink( ValueInternalLink *link ) + { + link->~ValueInternalLink(); + linksAllocator_.release( link ); + } +private: + BatchAllocator<ValueInternalMap,1> mapsAllocator_; + BatchAllocator<ValueInternalLink,1> linksAllocator_; +}; +#endif + +static ValueMapAllocator *&mapAllocator() +{ + static DefaultValueMapAllocator defaultAllocator; + static ValueMapAllocator *mapAllocator = &defaultAllocator; + return mapAllocator; +} + +static struct DummyMapAllocatorInitializer { + DummyMapAllocatorInitializer() + { + mapAllocator(); // ensure mapAllocator() statics are initialized before main(). + } +} dummyMapAllocatorInitializer; + + + +// h(K) = value * K >> w ; with w = 32 & K prime w.r.t. 2^32. + +/* +use linked list hash map. +buckets array is a container. +linked list element contains 6 key/values. (memory = (16+4) * 6 + 4 = 124) +value have extra state: valid, available, deleted +*/ + + +ValueInternalMap::ValueInternalMap() + : buckets_( 0 ) + , tailLink_( 0 ) + , bucketsSize_( 0 ) + , itemCount_( 0 ) +{ +} + + +ValueInternalMap::ValueInternalMap( const ValueInternalMap &other ) + : buckets_( 0 ) + , tailLink_( 0 ) + , bucketsSize_( 0 ) + , itemCount_( 0 ) +{ + reserve( other.itemCount_ ); + IteratorState it; + IteratorState itEnd; + other.makeBeginIterator( it ); + other.makeEndIterator( itEnd ); + for ( ; !equals(it,itEnd); increment(it) ) + { + bool isStatic; + const char *memberName = key( it, isStatic ); + const Value &aValue = value( it ); + resolveReference(memberName, isStatic) = aValue; + } +} + + +ValueInternalMap & +ValueInternalMap::operator =( const ValueInternalMap &other ) +{ + ValueInternalMap dummy( other ); + swap( dummy ); + return *this; +} + + +ValueInternalMap::~ValueInternalMap() +{ + if ( buckets_ ) + { + for ( BucketIndex bucketIndex =0; bucketIndex < bucketsSize_; ++bucketIndex ) + { + ValueInternalLink *link = buckets_[bucketIndex].next_; + while ( link ) + { + ValueInternalLink *linkToRelease = link; + link = link->next_; + mapAllocator()->releaseMapLink( linkToRelease ); + } + } + mapAllocator()->releaseMapBuckets( buckets_ ); + } +} + + +void +ValueInternalMap::swap( ValueInternalMap &other ) +{ + ValueInternalLink *tempBuckets = buckets_; + buckets_ = other.buckets_; + other.buckets_ = tempBuckets; + ValueInternalLink *tempTailLink = tailLink_; + tailLink_ = other.tailLink_; + other.tailLink_ = tempTailLink; + BucketIndex tempBucketsSize = bucketsSize_; + bucketsSize_ = other.bucketsSize_; + other.bucketsSize_ = tempBucketsSize; + BucketIndex tempItemCount = itemCount_; + itemCount_ = other.itemCount_; + other.itemCount_ = tempItemCount; +} + + +void +ValueInternalMap::clear() +{ + ValueInternalMap dummy; + swap( dummy ); +} + + +ValueInternalMap::BucketIndex +ValueInternalMap::size() const +{ + return itemCount_; +} + +bool +ValueInternalMap::reserveDelta( BucketIndex growth ) +{ + return reserve( itemCount_ + growth ); +} + +bool +ValueInternalMap::reserve( BucketIndex newItemCount ) +{ + if ( !buckets_ && newItemCount > 0 ) + { + buckets_ = mapAllocator()->allocateMapBuckets( 1 ); + bucketsSize_ = 1; + tailLink_ = &buckets_[0]; + } +// BucketIndex idealBucketCount = (newItemCount + ValueInternalLink::itemPerLink) / ValueInternalLink::itemPerLink; + return true; +} + + +const Value * +ValueInternalMap::find( const char *key ) const +{ + if ( !bucketsSize_ ) + return 0; + HashKey hashedKey = hash( key ); + BucketIndex bucketIndex = hashedKey % bucketsSize_; + for ( const ValueInternalLink *current = &buckets_[bucketIndex]; + current != 0; + current = current->next_ ) + { + for ( BucketIndex index=0; index < ValueInternalLink::itemPerLink; ++index ) + { + if ( current->items_[index].isItemAvailable() ) + return 0; + if ( strcmp( key, current->keys_[index] ) == 0 ) + return ¤t->items_[index]; + } + } + return 0; +} + + +Value * +ValueInternalMap::find( const char *key ) +{ + const ValueInternalMap *constThis = this; + return const_cast<Value *>( constThis->find( key ) ); +} + + +Value & +ValueInternalMap::resolveReference( const char *key, + bool isStatic ) +{ + HashKey hashedKey = hash( key ); + if ( bucketsSize_ ) + { + BucketIndex bucketIndex = hashedKey % bucketsSize_; + ValueInternalLink **previous = 0; + BucketIndex index; + for ( ValueInternalLink *current = &buckets_[bucketIndex]; + current != 0; + previous = ¤t->next_, current = current->next_ ) + { + for ( index=0; index < ValueInternalLink::itemPerLink; ++index ) + { + if ( current->items_[index].isItemAvailable() ) + return setNewItem( key, isStatic, current, index ); + if ( strcmp( key, current->keys_[index] ) == 0 ) + return current->items_[index]; + } + } + } + + reserveDelta( 1 ); + return unsafeAdd( key, isStatic, hashedKey ); +} + + +void +ValueInternalMap::remove( const char *key ) +{ + HashKey hashedKey = hash( key ); + if ( !bucketsSize_ ) + return; + BucketIndex bucketIndex = hashedKey % bucketsSize_; + for ( ValueInternalLink *link = &buckets_[bucketIndex]; + link != 0; + link = link->next_ ) + { + BucketIndex index; + for ( index =0; index < ValueInternalLink::itemPerLink; ++index ) + { + if ( link->items_[index].isItemAvailable() ) + return; + if ( strcmp( key, link->keys_[index] ) == 0 ) + { + doActualRemove( link, index, bucketIndex ); + return; + } + } + } +} + +void +ValueInternalMap::doActualRemove( ValueInternalLink *link, + BucketIndex index, + BucketIndex bucketIndex ) +{ + // find last item of the bucket and swap it with the 'removed' one. + // set removed items flags to 'available'. + // if last page only contains 'available' items, then desallocate it (it's empty) + ValueInternalLink *&lastLink = getLastLinkInBucket( index ); + BucketIndex lastItemIndex = 1; // a link can never be empty, so start at 1 + for ( ; + lastItemIndex < ValueInternalLink::itemPerLink; + ++lastItemIndex ) // may be optimized with dicotomic search + { + if ( lastLink->items_[lastItemIndex].isItemAvailable() ) + break; + } + + BucketIndex lastUsedIndex = lastItemIndex - 1; + Value *valueToDelete = &link->items_[index]; + Value *valueToPreserve = &lastLink->items_[lastUsedIndex]; + if ( valueToDelete != valueToPreserve ) + valueToDelete->swap( *valueToPreserve ); + if ( lastUsedIndex == 0 ) // page is now empty + { // remove it from bucket linked list and delete it. + ValueInternalLink *linkPreviousToLast = lastLink->previous_; + if ( linkPreviousToLast != 0 ) // can not deleted bucket link. + { + mapAllocator()->releaseMapLink( lastLink ); + linkPreviousToLast->next_ = 0; + lastLink = linkPreviousToLast; + } + } + else + { + Value dummy; + valueToPreserve->swap( dummy ); // restore deleted to default Value. + valueToPreserve->setItemUsed( false ); + } + --itemCount_; +} + + +ValueInternalLink *& +ValueInternalMap::getLastLinkInBucket( BucketIndex bucketIndex ) +{ + if ( bucketIndex == bucketsSize_ - 1 ) + return tailLink_; + ValueInternalLink *&previous = buckets_[bucketIndex+1].previous_; + if ( !previous ) + previous = &buckets_[bucketIndex]; + return previous; +} + + +Value & +ValueInternalMap::setNewItem( const char *key, + bool isStatic, + ValueInternalLink *link, + BucketIndex index ) +{ + char *duplicatedKey = valueAllocator()->makeMemberName( key ); + ++itemCount_; + link->keys_[index] = duplicatedKey; + link->items_[index].setItemUsed(); + link->items_[index].setMemberNameIsStatic( isStatic ); + return link->items_[index]; // items already default constructed. +} + + +Value & +ValueInternalMap::unsafeAdd( const char *key, + bool isStatic, + HashKey hashedKey ) +{ + JSON_ASSERT_MESSAGE( bucketsSize_ > 0, "ValueInternalMap::unsafeAdd(): internal logic error." ); + BucketIndex bucketIndex = hashedKey % bucketsSize_; + ValueInternalLink *&previousLink = getLastLinkInBucket( bucketIndex ); + ValueInternalLink *link = previousLink; + BucketIndex index; + for ( index =0; index < ValueInternalLink::itemPerLink; ++index ) + { + if ( link->items_[index].isItemAvailable() ) + break; + } + if ( index == ValueInternalLink::itemPerLink ) // need to add a new page + { + ValueInternalLink *newLink = mapAllocator()->allocateMapLink(); + index = 0; + link->next_ = newLink; + previousLink = newLink; + link = newLink; + } + return setNewItem( key, isStatic, link, index ); +} + + +ValueInternalMap::HashKey +ValueInternalMap::hash( const char *key ) const +{ + HashKey hash = 0; + while ( *key ) + hash += *key++ * 37; + return hash; +} + + +int +ValueInternalMap::compare( const ValueInternalMap &other ) const +{ + int sizeDiff( itemCount_ - other.itemCount_ ); + if ( sizeDiff != 0 ) + return sizeDiff; + // Strict order guaranty is required. Compare all keys FIRST, then compare values. + IteratorState it; + IteratorState itEnd; + makeBeginIterator( it ); + makeEndIterator( itEnd ); + for ( ; !equals(it,itEnd); increment(it) ) + { + if ( !other.find( key( it ) ) ) + return 1; + } + + // All keys are equals, let's compare values + makeBeginIterator( it ); + for ( ; !equals(it,itEnd); increment(it) ) + { + const Value *otherValue = other.find( key( it ) ); + int valueDiff = value(it).compare( *otherValue ); + if ( valueDiff != 0 ) + return valueDiff; + } + return 0; +} + + +void +ValueInternalMap::makeBeginIterator( IteratorState &it ) const +{ + it.map_ = const_cast<ValueInternalMap *>( this ); + it.bucketIndex_ = 0; + it.itemIndex_ = 0; + it.link_ = buckets_; +} + + +void +ValueInternalMap::makeEndIterator( IteratorState &it ) const +{ + it.map_ = const_cast<ValueInternalMap *>( this ); + it.bucketIndex_ = bucketsSize_; + it.itemIndex_ = 0; + it.link_ = 0; +} + + +bool +ValueInternalMap::equals( const IteratorState &x, const IteratorState &other ) +{ + return x.map_ == other.map_ + && x.bucketIndex_ == other.bucketIndex_ + && x.link_ == other.link_ + && x.itemIndex_ == other.itemIndex_; +} + + +void +ValueInternalMap::incrementBucket( IteratorState &iterator ) +{ + ++iterator.bucketIndex_; + JSON_ASSERT_MESSAGE( iterator.bucketIndex_ <= iterator.map_->bucketsSize_, + "ValueInternalMap::increment(): attempting to iterate beyond end." ); + if ( iterator.bucketIndex_ == iterator.map_->bucketsSize_ ) + iterator.link_ = 0; + else + iterator.link_ = &(iterator.map_->buckets_[iterator.bucketIndex_]); + iterator.itemIndex_ = 0; +} + + +void +ValueInternalMap::increment( IteratorState &iterator ) +{ + JSON_ASSERT_MESSAGE( iterator.map_, "Attempting to iterator using invalid iterator." ); + ++iterator.itemIndex_; + if ( iterator.itemIndex_ == ValueInternalLink::itemPerLink ) + { + JSON_ASSERT_MESSAGE( iterator.link_ != 0, + "ValueInternalMap::increment(): attempting to iterate beyond end." ); + iterator.link_ = iterator.link_->next_; + if ( iterator.link_ == 0 ) + incrementBucket( iterator ); + } + else if ( iterator.link_->items_[iterator.itemIndex_].isItemAvailable() ) + { + incrementBucket( iterator ); + } +} + + +void +ValueInternalMap::decrement( IteratorState &iterator ) +{ + if ( iterator.itemIndex_ == 0 ) + { + JSON_ASSERT_MESSAGE( iterator.map_, "Attempting to iterate using invalid iterator." ); + if ( iterator.link_ == &iterator.map_->buckets_[iterator.bucketIndex_] ) + { + JSON_ASSERT_MESSAGE( iterator.bucketIndex_ > 0, "Attempting to iterate beyond beginning." ); + --(iterator.bucketIndex_); + } + iterator.link_ = iterator.link_->previous_; + iterator.itemIndex_ = ValueInternalLink::itemPerLink - 1; + } +} + + +const char * +ValueInternalMap::key( const IteratorState &iterator ) +{ + JSON_ASSERT_MESSAGE( iterator.link_, "Attempting to iterate using invalid iterator." ); + return iterator.link_->keys_[iterator.itemIndex_]; +} + +const char * +ValueInternalMap::key( const IteratorState &iterator, bool &isStatic ) +{ + JSON_ASSERT_MESSAGE( iterator.link_, "Attempting to iterate using invalid iterator." ); + isStatic = iterator.link_->items_[iterator.itemIndex_].isMemberNameStatic(); + return iterator.link_->keys_[iterator.itemIndex_]; +} + + +Value & +ValueInternalMap::value( const IteratorState &iterator ) +{ + JSON_ASSERT_MESSAGE( iterator.link_, "Attempting to iterate using invalid iterator." ); + return iterator.link_->items_[iterator.itemIndex_]; +} + + +int +ValueInternalMap::distance( const IteratorState &x, const IteratorState &y ) +{ + int offset = 0; + IteratorState it = x; + while ( !equals( it, y ) ) + increment( it ); + return offset; +} diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_reader.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_reader.cpp new file mode 100644 index 00000000..5af16c8d --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_reader.cpp @@ -0,0 +1,892 @@ +#include <json/reader.h> +#include <json/value.h> +#include <utility> +#include <cstdio> +#include <cassert> +#include <cstring> +#include <iostream> +#include <stdexcept> + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +// QNX is strict about declaring C symbols in the std namespace. +#ifdef __QNXNTO__ +using std::memcpy; +using std::sprintf; +using std::sscanf; +#endif + +// Implementation of class Features +// //////////////////////////////// + +Features::Features() + : allowComments_( true ) + , strictRoot_( false ) +{ +} + + +Features +Features::all() +{ + return Features(); +} + + +Features +Features::strictMode() +{ + Features features; + features.allowComments_ = false; + features.strictRoot_ = true; + return features; +} + +// Implementation of class Reader +// //////////////////////////////// + + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4; +} + +static inline bool +in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 ) +{ + return c == c1 || c == c2 || c == c3 || c == c4 || c == c5; +} + + +static bool +containsNewLine( Reader::Location begin, + Reader::Location end ) +{ + for ( ;begin < end; ++begin ) + if ( *begin == '\n' || *begin == '\r' ) + return true; + return false; +} + +static std::string codePointToUTF8(unsigned int cp) +{ + std::string result; + + // based on description from http://en.wikipedia.org/wiki/UTF-8 + + if (cp <= 0x7f) + { + result.resize(1); + result[0] = static_cast<char>(cp); + } + else if (cp <= 0x7FF) + { + result.resize(2); + result[1] = static_cast<char>(0x80 | (0x3f & cp)); + result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6))); + } + else if (cp <= 0xFFFF) + { + result.resize(3); + result[2] = static_cast<char>(0x80 | (0x3f & cp)); + result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6))); + result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12))); + } + else if (cp <= 0x10FFFF) + { + result.resize(4); + result[3] = static_cast<char>(0x80 | (0x3f & cp)); + result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); + result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12))); + result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18))); + } + + return result; +} + + +// Class Reader +// ////////////////////////////////////////////////////////////////// + +Reader::Reader() + : features_( Features::all() ) +{ +} + + +Reader::Reader( const Features &features ) + : features_( features ) +{ +} + + +bool +Reader::parse( const std::string &document, + Value &root, + bool collectComments ) +{ + document_ = document; + const char *begin = document_.c_str(); + const char *end = begin + document_.length(); + return parse( begin, end, root, collectComments ); +} + + +bool +Reader::parse( std::istream& sin, + Value &root, + bool collectComments ) +{ + //std::istream_iterator<char> begin(sin); + //std::istream_iterator<char> end; + // Those would allow streamed input from a file, if parse() were a + // template function. + + // Since std::string is reference-counted, this at least does not + // create an extra copy. + std::string doc; + std::getline(sin, doc, (char)EOF); + return parse( doc, root, collectComments ); +} + +bool +Reader::parse( const char *beginDoc, const char *endDoc, + Value &root, + bool collectComments ) +{ + if ( !features_.allowComments_ ) + { + collectComments = false; + } + + begin_ = beginDoc; + end_ = endDoc; + collectComments_ = collectComments; + current_ = begin_; + lastValueEnd_ = 0; + lastValue_ = 0; + commentsBefore_ = ""; + errors_.clear(); + while ( !nodes_.empty() ) + nodes_.pop(); + nodes_.push( &root ); + + bool successful = readValue(); + Token token; + skipCommentTokens( token ); + if ( collectComments_ && !commentsBefore_.empty() ) + root.setComment( commentsBefore_, commentAfter ); + if ( features_.strictRoot_ ) + { + if ( !root.isArray() && !root.isObject() ) + { + // Set error location to start of doc, ideally should be first token found in doc + token.type_ = tokenError; + token.start_ = beginDoc; + token.end_ = endDoc; + addError( "A valid JSON document must be either an array or an object value.", + token ); + return false; + } + } + return successful; +} + + +bool +Reader::readValue() +{ + Token token; + skipCommentTokens( token ); + bool successful = true; + + if ( collectComments_ && !commentsBefore_.empty() ) + { + currentValue().setComment( commentsBefore_, commentBefore ); + commentsBefore_ = ""; + } + + + switch ( token.type_ ) + { + case tokenObjectBegin: + successful = readObject( token ); + break; + case tokenArrayBegin: + successful = readArray( token ); + break; + case tokenNumber: + successful = decodeNumber( token ); + break; + case tokenString: + successful = decodeString( token ); + break; + case tokenTrue: + currentValue() = true; + break; + case tokenFalse: + currentValue() = false; + break; + case tokenNull: + currentValue() = Value(); + break; + default: + return addError( "Syntax error: value, object or array expected.", token ); + } + + if ( collectComments_ ) + { + lastValueEnd_ = current_; + lastValue_ = ¤tValue(); + } + + return successful; +} + + +void +Reader::skipCommentTokens( Token &token ) +{ + if ( features_.allowComments_ ) + { + do + { + readToken( token ); + } + while ( token.type_ == tokenComment ); + } + else + { + readToken( token ); + } +} + + +bool +Reader::expectToken( TokenType type, Token &token, const char *message ) +{ + readToken( token ); + if ( token.type_ != type ) + return addError( message, token ); + return true; +} + + +bool +Reader::readToken( Token &token ) +{ + skipSpaces(); + token.start_ = current_; + Char c = getNextChar(); + bool ok = true; + switch ( c ) + { + case '{': + token.type_ = tokenObjectBegin; + break; + case '}': + token.type_ = tokenObjectEnd; + break; + case '[': + token.type_ = tokenArrayBegin; + break; + case ']': + token.type_ = tokenArrayEnd; + break; + case '"': + token.type_ = tokenString; + ok = readString(); + break; + case '/': + token.type_ = tokenComment; + ok = readComment(); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + token.type_ = tokenNumber; + readNumber(); + break; + case 't': + token.type_ = tokenTrue; + ok = match( "rue", 3 ); + break; + case 'f': + token.type_ = tokenFalse; + ok = match( "alse", 4 ); + break; + case 'n': + token.type_ = tokenNull; + ok = match( "ull", 3 ); + break; + case ',': + token.type_ = tokenArraySeparator; + break; + case ':': + token.type_ = tokenMemberSeparator; + break; + case 0: + token.type_ = tokenEndOfStream; + break; + default: + ok = false; + break; + } + if ( !ok ) + token.type_ = tokenError; + token.end_ = current_; + return true; +} + + +void +Reader::skipSpaces() +{ + while ( current_ != end_ ) + { + Char c = *current_; + if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' ) + ++current_; + else + break; + } +} + + +bool +Reader::match( Location pattern, + int patternLength ) +{ + if ( end_ - current_ < patternLength ) + return false; + int index = patternLength; + while ( index-- ) + if ( current_[index] != pattern[index] ) + return false; + current_ += patternLength; + return true; +} + + +bool +Reader::readComment() +{ + Location commentBegin = current_ - 1; + Char c = getNextChar(); + bool successful = false; + if ( c == '*' ) + successful = readCStyleComment(); + else if ( c == '/' ) + successful = readCppStyleComment(); + if ( !successful ) + return false; + + if ( collectComments_ ) + { + CommentPlacement placement = commentBefore; + if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) ) + { + if ( c != '*' || !containsNewLine( commentBegin, current_ ) ) + placement = commentAfterOnSameLine; + } + + addComment( commentBegin, current_, placement ); + } + return true; +} + + +void +Reader::addComment( Location begin, + Location end, + CommentPlacement placement ) +{ + assert( collectComments_ ); + if ( placement == commentAfterOnSameLine ) + { + assert( lastValue_ != 0 ); + lastValue_->setComment( std::string( begin, end ), placement ); + } + else + { + if ( !commentsBefore_.empty() ) + commentsBefore_ += "\n"; + commentsBefore_ += std::string( begin, end ); + } +} + + +bool +Reader::readCStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '*' && *current_ == '/' ) + break; + } + return getNextChar() == '/'; +} + + +bool +Reader::readCppStyleComment() +{ + while ( current_ != end_ ) + { + Char c = getNextChar(); + if ( c == '\r' || c == '\n' ) + break; + } + return true; +} + + +void +Reader::readNumber() +{ + while ( current_ != end_ ) + { + if ( !(*current_ >= '0' && *current_ <= '9') && + !in( *current_, '.', 'e', 'E', '+', '-' ) ) + break; + ++current_; + } +} + +bool +Reader::readString() +{ + Char c = 0; + while ( current_ != end_ ) + { + c = getNextChar(); + if ( c == '\\' ) + getNextChar(); + else if ( c == '"' ) + break; + } + return c == '"'; +} + + +bool +Reader::readObject( Token &tokenStart ) +{ + Token tokenName; + std::string name; + currentValue() = Value( objectValue ); + while ( readToken( tokenName ) ) + { + bool initialTokenOk = true; + while ( tokenName.type_ == tokenComment && initialTokenOk ) + initialTokenOk = readToken( tokenName ); + if ( !initialTokenOk ) + break; + if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object + return true; + if ( tokenName.type_ != tokenString ) + break; + + name = ""; + if ( !decodeString( tokenName, name ) ) + return recoverFromError( tokenObjectEnd ); + + Token colon; + if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator ) + { + return addErrorAndRecover( "Missing ':' after object member name", + colon, + tokenObjectEnd ); + } + Value &value = currentValue()[ name ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenObjectEnd ); + + Token comma; + if ( !readToken( comma ) + || ( comma.type_ != tokenObjectEnd && + comma.type_ != tokenArraySeparator && + comma.type_ != tokenComment ) ) + { + return addErrorAndRecover( "Missing ',' or '}' in object declaration", + comma, + tokenObjectEnd ); + } + bool finalizeTokenOk = true; + while ( comma.type_ == tokenComment && + finalizeTokenOk ) + finalizeTokenOk = readToken( comma ); + if ( comma.type_ == tokenObjectEnd ) + return true; + } + return addErrorAndRecover( "Missing '}' or object member name", + tokenName, + tokenObjectEnd ); +} + + +bool +Reader::readArray( Token &tokenStart ) +{ + currentValue() = Value( arrayValue ); + skipSpaces(); + if ( *current_ == ']' ) // empty array + { + Token endArray; + readToken( endArray ); + return true; + } + int index = 0; + while ( true ) + { + Value &value = currentValue()[ index++ ]; + nodes_.push( &value ); + bool ok = readValue(); + nodes_.pop(); + if ( !ok ) // error already set + return recoverFromError( tokenArrayEnd ); + + Token token; + // Accept Comment after last item in the array. + ok = readToken( token ); + while ( token.type_ == tokenComment && ok ) + { + ok = readToken( token ); + } + bool badTokenType = ( token.type_ == tokenArraySeparator && + token.type_ == tokenArrayEnd ); + if ( !ok || badTokenType ) + { + return addErrorAndRecover( "Missing ',' or ']' in array declaration", + token, + tokenArrayEnd ); + } + if ( token.type_ == tokenArrayEnd ) + break; + } + return true; +} + + +bool +Reader::decodeNumber( Token &token ) +{ + bool isDouble = false; + for ( Location inspect = token.start_; inspect != token.end_; ++inspect ) + { + isDouble = isDouble + || in( *inspect, '.', 'e', 'E', '+' ) + || ( *inspect == '-' && inspect != token.start_ ); + } + if ( isDouble ) + return decodeDouble( token ); + Location current = token.start_; + bool isNegative = *current == '-'; + if ( isNegative ) + ++current; + Value::UInt threshold = (isNegative ? Value::UInt(-Value::minInt) + : Value::maxUInt) / 10; + Value::UInt value = 0; + while ( current < token.end_ ) + { + Char c = *current++; + if ( c < '0' || c > '9' ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + if ( value >= threshold ) + return decodeDouble( token ); + value = value * 10 + Value::UInt(c - '0'); + } + if ( isNegative ) + currentValue() = -Value::Int( value ); + else if ( value <= Value::UInt(Value::maxInt) ) + currentValue() = Value::Int( value ); + else + currentValue() = value; + return true; +} + + +bool +Reader::decodeDouble( Token &token ) +{ + double value = 0; + const int bufferSize = 32; + int count; + int length = int(token.end_ - token.start_); + if ( length <= bufferSize ) + { + Char buffer[bufferSize]; + memcpy( buffer, token.start_, length ); + buffer[length] = 0; + count = sscanf( buffer, "%lf", &value ); + } + else + { + std::string buffer( token.start_, token.end_ ); + count = sscanf( buffer.c_str(), "%lf", &value ); + } + + if ( count != 1 ) + return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); + currentValue() = value; + return true; +} + + +bool +Reader::decodeString( Token &token ) +{ + std::string decoded; + if ( !decodeString( token, decoded ) ) + return false; + currentValue() = decoded; + return true; +} + + +bool +Reader::decodeString( Token &token, std::string &decoded ) +{ + decoded.reserve( token.end_ - token.start_ - 2 ); + Location current = token.start_ + 1; // skip '"' + Location end = token.end_ - 1; // do not include '"' + while ( current != end ) + { + Char c = *current++; + if ( c == '"' ) + break; + else if ( c == '\\' ) + { + if ( current == end ) + return addError( "Empty escape sequence in string", token, current ); + Char escape = *current++; + switch ( escape ) + { + case '"': decoded += '"'; break; + case '/': decoded += '/'; break; + case '\\': decoded += '\\'; break; + case 'b': decoded += '\b'; break; + case 'f': decoded += '\f'; break; + case 'n': decoded += '\n'; break; + case 'r': decoded += '\r'; break; + case 't': decoded += '\t'; break; + case 'u': + { + unsigned int unicode; + if ( !decodeUnicodeCodePoint( token, current, end, unicode ) ) + return false; + decoded += codePointToUTF8(unicode); + } + break; + default: + return addError( "Bad escape sequence in string", token, current ); + } + } + else + { + decoded += c; + } + } + return true; +} + +bool +Reader::decodeUnicodeCodePoint( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + + if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) ) + return false; + if (unicode >= 0xD800 && unicode <= 0xDBFF) + { + // surrogate pairs + if (end - current < 6) + return addError( "additional six characters expected to parse unicode surrogate pair.", token, current ); + unsigned int surrogatePair; + if (*(current++) == '\\' && *(current++)== 'u') + { + if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair )) + { + unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); + } + else + return false; + } + else + return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current ); + } + return true; +} + +bool +Reader::decodeUnicodeEscapeSequence( Token &token, + Location ¤t, + Location end, + unsigned int &unicode ) +{ + if ( end - current < 4 ) + return addError( "Bad unicode escape sequence in string: four digits expected.", token, current ); + unicode = 0; + for ( int index =0; index < 4; ++index ) + { + Char c = *current++; + unicode *= 16; + if ( c >= '0' && c <= '9' ) + unicode += c - '0'; + else if ( c >= 'a' && c <= 'f' ) + unicode += c - 'a' + 10; + else if ( c >= 'A' && c <= 'F' ) + unicode += c - 'A' + 10; + else + return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current ); + } + return true; +} + + +bool +Reader::addError( const std::string &message, + Token &token, + Location extra ) +{ + ErrorInfo info; + info.token_ = token; + info.message_ = message; + info.extra_ = extra; + errors_.push_back( info ); + return false; +} + + +bool +Reader::recoverFromError( TokenType skipUntilToken ) +{ + int errorCount = int(errors_.size()); + Token skip; + while ( true ) + { + if ( !readToken(skip) ) + errors_.resize( errorCount ); // discard errors caused by recovery + if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream ) + break; + } + errors_.resize( errorCount ); + return false; +} + + +bool +Reader::addErrorAndRecover( const std::string &message, + Token &token, + TokenType skipUntilToken ) +{ + addError( message, token ); + return recoverFromError( skipUntilToken ); +} + + +Value & +Reader::currentValue() +{ + return *(nodes_.top()); +} + + +Reader::Char +Reader::getNextChar() +{ + if ( current_ == end_ ) + return 0; + return *current_++; +} + + +void +Reader::getLocationLineAndColumn( Location location, + int &line, + int &column ) const +{ + Location current = begin_; + Location lastLineStart = current; + line = 0; + while ( current < location && current != end_ ) + { + Char c = *current++; + if ( c == '\r' ) + { + if ( *current == '\n' ) + ++current; + lastLineStart = current; + ++line; + } + else if ( c == '\n' ) + { + lastLineStart = current; + ++line; + } + } + // column & line start at 1 + column = int(location - lastLineStart) + 1; + ++line; +} + + +std::string +Reader::getLocationLineAndColumn( Location location ) const +{ + int line, column; + getLocationLineAndColumn( location, line, column ); + char buffer[18+16+16+1]; + sprintf( buffer, "Line %d, Column %d", line, column ); + return buffer; +} + + +std::string +Reader::getFormatedErrorMessages() const +{ + std::string formattedMessage; + for ( Errors::const_iterator itError = errors_.begin(); + itError != errors_.end(); + ++itError ) + { + const ErrorInfo &error = *itError; + formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n"; + formattedMessage += " " + error.message_ + "\n"; + if ( error.extra_ ) + formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n"; + } + return formattedMessage; +} + + +std::istream& operator>>( std::istream &sin, Value &root ) +{ + Json::Reader reader; + bool ok = reader.parse(sin, root, true); + //JSON_ASSERT( ok ); + if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages()); + return sin; +} + + +} // namespace Json diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_value.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_value.cpp new file mode 100644 index 00000000..6e5dcd3e --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_value.cpp @@ -0,0 +1,1726 @@ +#include <iostream> +#include <json/value.h> +#include <json/writer.h> +#include <utility> +#include <stdexcept> +#include <cstring> +#include <cassert> +#ifdef JSON_USE_CPPTL +# include <cpptl/conststring.h> +#endif +#include <cstddef> // size_t +#ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR +# include "json_batchallocator.h" +#endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR + +#define JSON_ASSERT_UNREACHABLE assert( false ) +#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw +#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) throw std::runtime_error( message ); + +namespace Json { + +// QNX is strict about declaring C symbols in the std namespace. +#ifdef __QNXNTO__ +using std::memcpy; +using std::strchr; +using std::strcmp; +using std::strlen; +#endif + +const Value Value::null; +const Int Value::minInt = Int( ~(UInt(-1)/2) ); +const Int Value::maxInt = Int( UInt(-1)/2 ); +const UInt Value::maxUInt = UInt(-1); + +// A "safe" implementation of strdup. Allow null pointer to be passed. +// Also avoid warning on msvc80. +// +//inline char *safeStringDup( const char *czstring ) +//{ +// if ( czstring ) +// { +// const size_t length = (unsigned int)( strlen(czstring) + 1 ); +// char *newString = static_cast<char *>( malloc( length ) ); +// memcpy( newString, czstring, length ); +// return newString; +// } +// return 0; +//} +// +//inline char *safeStringDup( const std::string &str ) +//{ +// if ( !str.empty() ) +// { +// const size_t length = str.length(); +// char *newString = static_cast<char *>( malloc( length + 1 ) ); +// memcpy( newString, str.c_str(), length ); +// newString[length] = 0; +// return newString; +// } +// return 0; +//} + +ValueAllocator::~ValueAllocator() +{ +} + +class DefaultValueAllocator : public ValueAllocator +{ +public: + virtual ~DefaultValueAllocator() + { + } + + virtual char *makeMemberName( const char *memberName ) + { + return duplicateStringValue( memberName ); + } + + virtual void releaseMemberName( char *memberName ) + { + releaseStringValue( memberName ); + } + + virtual char *duplicateStringValue( const char *value, + unsigned int length = unknown ) + { + //@todo invesgate this old optimization + //if ( !value || value[0] == 0 ) + // return 0; + + if ( length == unknown ) + length = (unsigned int)strlen(value); + char *newString = static_cast<char *>( malloc( length + 1 ) ); + memcpy( newString, value, length ); + newString[length] = 0; + return newString; + } + + virtual void releaseStringValue( char *value ) + { + if ( value ) + free( value ); + } +}; + +static ValueAllocator *&valueAllocator() +{ + static DefaultValueAllocator defaultAllocator; + static ValueAllocator *valueAllocator = &defaultAllocator; + return valueAllocator; +} + +static struct DummyValueAllocatorInitializer { + DummyValueAllocatorInitializer() + { + valueAllocator(); // ensure valueAllocator() statics are initialized before main(). + } +} dummyValueAllocatorInitializer; + + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ValueInternals... +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +#ifdef JSON_VALUE_USE_INTERNAL_MAP +# include "json_internalarray.inl" +# include "json_internalmap.inl" +#endif // JSON_VALUE_USE_INTERNAL_MAP + +# include "json_valueiterator.inl" + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CommentInfo +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + + +Value::CommentInfo::CommentInfo() + : comment_( 0 ) +{ +} + +Value::CommentInfo::~CommentInfo() +{ + if ( comment_ ) + valueAllocator()->releaseStringValue( comment_ ); +} + + +void +Value::CommentInfo::setComment( const char *text ) +{ + if ( comment_ ) + valueAllocator()->releaseStringValue( comment_ ); + JSON_ASSERT( text ); + JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /"); + // It seems that /**/ style comments are acceptable as well. + comment_ = valueAllocator()->duplicateStringValue( text ); +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::CZString +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +# ifndef JSON_VALUE_USE_INTERNAL_MAP + +// Notes: index_ indicates if the string was allocated when +// a string is stored. + +Value::CZString::CZString( int index ) + : cstr_( 0 ) + , index_( index ) +{ +} + +Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate ) + : cstr_( allocate == duplicate ? valueAllocator()->makeMemberName(cstr) + : cstr ) + , index_( allocate ) +{ +} + +Value::CZString::CZString( const CZString &other ) +: cstr_( other.index_ != noDuplication && other.cstr_ != 0 + ? valueAllocator()->makeMemberName( other.cstr_ ) + : other.cstr_ ) + , index_( other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) + : other.index_ ) +{ +} + +Value::CZString::~CZString() +{ + if ( cstr_ && index_ == duplicate ) + valueAllocator()->releaseMemberName( const_cast<char *>( cstr_ ) ); +} + +void +Value::CZString::swap( CZString &other ) +{ + std::swap( cstr_, other.cstr_ ); + std::swap( index_, other.index_ ); +} + +Value::CZString & +Value::CZString::operator =( const CZString &other ) +{ + CZString temp( other ); + swap( temp ); + return *this; +} + +bool +Value::CZString::operator<( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) < 0; + return index_ < other.index_; +} + +bool +Value::CZString::operator==( const CZString &other ) const +{ + if ( cstr_ ) + return strcmp( cstr_, other.cstr_ ) == 0; + return index_ == other.index_; +} + + +int +Value::CZString::index() const +{ + return index_; +} + + +const char * +Value::CZString::c_str() const +{ + return cstr_; +} + +bool +Value::CZString::isStaticString() const +{ + return index_ == noDuplication; +} + +#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class Value::Value +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +/*! \internal Default constructor initialization must be equivalent to: + * memset( this, 0, sizeof(Value) ) + * This optimization is used in ValueInternalMap fast allocator. + */ +Value::Value( ValueType type ) + : type_( type ) + , allocated_( 0 ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type ) + { + case nullValue: + break; + case intValue: + case uintValue: + value_.int_ = 0; + break; + case realValue: + value_.real_ = 0.0; + break; + case stringValue: + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues(); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArray(); + break; + case objectValue: + value_.map_ = mapAllocator()->newMap(); + break; +#endif + case booleanValue: + value_.bool_ = false; + break; + default: + JSON_ASSERT_UNREACHABLE; + } +} + + +Value::Value( Int value ) + : type_( intValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.int_ = value; +} + + +Value::Value( UInt value ) + : type_( uintValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.uint_ = value; +} + +Value::Value( double value ) + : type_( realValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.real_ = value; +} + +Value::Value( const char *value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = valueAllocator()->duplicateStringValue( value ); +} + + +Value::Value( const char *beginValue, + const char *endValue ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = valueAllocator()->duplicateStringValue( beginValue, + UInt(endValue - beginValue) ); +} + + +Value::Value( const std::string &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = valueAllocator()->duplicateStringValue( value.c_str(), + (unsigned int)value.length() ); + +} + +Value::Value( const StaticString &value ) + : type_( stringValue ) + , allocated_( false ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = const_cast<char *>( value.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +Value::Value( const CppTL::ConstString &value ) + : type_( stringValue ) + , allocated_( true ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.string_ = valueAllocator()->duplicateStringValue( value, value.length() ); +} +# endif + +Value::Value( bool value ) + : type_( booleanValue ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + value_.bool_ = value; +} + + +Value::Value( const Value &other ) + : type_( other.type_ ) + , comments_( 0 ) +# ifdef JSON_VALUE_USE_INTERNAL_MAP + , itemIsUsed_( 0 ) +#endif +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + value_ = other.value_; + break; + case stringValue: + if ( other.value_.string_ ) + { + value_.string_ = valueAllocator()->duplicateStringValue( other.value_.string_ ); + allocated_ = true; + } + else + value_.string_ = 0; + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_ = new ObjectValues( *other.value_.map_ ); + break; +#else + case arrayValue: + value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ ); + break; + case objectValue: + value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + if ( other.comments_ ) + { + comments_ = new CommentInfo[numberOfCommentPlacement]; + for ( int comment =0; comment < numberOfCommentPlacement; ++comment ) + { + const CommentInfo &otherComment = other.comments_[comment]; + if ( otherComment.comment_ ) + comments_[comment].setComment( otherComment.comment_ ); + } + } +} + + +Value::~Value() +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + break; + case stringValue: + if ( allocated_ ) + valueAllocator()->releaseStringValue( value_.string_ ); + break; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + delete value_.map_; + break; +#else + case arrayValue: + arrayAllocator()->destructArray( value_.array_ ); + break; + case objectValue: + mapAllocator()->destructMap( value_.map_ ); + break; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + + if ( comments_ ) + delete[] comments_; +} + +Value & +Value::operator=( const Value &other ) +{ + Value temp( other ); + swap( temp ); + return *this; +} + +void +Value::swap( Value &other ) +{ + ValueType temp = type_; + type_ = other.type_; + other.type_ = temp; + std::swap( value_, other.value_ ); + int temp2 = allocated_; + allocated_ = other.allocated_; + other.allocated_ = temp2; +} + +ValueType +Value::type() const +{ + return type_; +} + + +int +Value::compare( const Value &other ) +{ + /* + int typeDelta = other.type_ - type_; + switch ( type_ ) + { + case nullValue: + + return other.type_ == type_; + case intValue: + if ( other.type_.isNumeric() + case uintValue: + case realValue: + case booleanValue: + break; + case stringValue, + break; + case arrayValue: + delete value_.array_; + break; + case objectValue: + delete value_.map_; + default: + JSON_ASSERT_UNREACHABLE; + } + */ + return 0; // unreachable +} + +bool +Value::operator <( const Value &other ) const +{ + int typeDelta = type_ - other.type_; + if ( typeDelta ) + return typeDelta < 0 ? true : false; + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + return value_.int_ < other.value_.int_; + case uintValue: + return value_.uint_ < other.value_.uint_; + case realValue: + return value_.real_ < other.value_.real_; + case booleanValue: + return value_.bool_ < other.value_.bool_; + case stringValue: + return ( value_.string_ == 0 && other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) < 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + { + int delta = int( value_.map_->size() - other.value_.map_->size() ); + if ( delta ) + return delta < 0; + return (*value_.map_) < (*other.value_.map_); + } +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) < 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) < 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable +} + +bool +Value::operator <=( const Value &other ) const +{ + return !(other > *this); +} + +bool +Value::operator >=( const Value &other ) const +{ + return !(*this < other); +} + +bool +Value::operator >( const Value &other ) const +{ + return other < *this; +} + +bool +Value::operator ==( const Value &other ) const +{ + //if ( type_ != other.type_ ) + // GCC 2.95.3 says: + // attempt to take address of bit-field structure member `Json::Value::type_' + // Beats me, but a temp solves the problem. + int temp = other.type_; + if ( type_ != temp ) + return false; + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return value_.int_ == other.value_.int_; + case uintValue: + return value_.uint_ == other.value_.uint_; + case realValue: + return value_.real_ == other.value_.real_; + case booleanValue: + return value_.bool_ == other.value_.bool_; + case stringValue: + return ( value_.string_ == other.value_.string_ ) + || ( other.value_.string_ + && value_.string_ + && strcmp( value_.string_, other.value_.string_ ) == 0 ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + return value_.map_->size() == other.value_.map_->size() + && (*value_.map_) == (*other.value_.map_); +#else + case arrayValue: + return value_.array_->compare( *(other.value_.array_) ) == 0; + case objectValue: + return value_.map_->compare( *(other.value_.map_) ) == 0; +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable +} + +bool +Value::operator !=( const Value &other ) const +{ + return !( *this == other ); +} + +const char * +Value::asCString() const +{ + JSON_ASSERT( type_ == stringValue ); + return value_.string_; +} + + +std::string +Value::asString() const +{ + switch ( type_ ) + { + case nullValue: + return ""; + case stringValue: + return value_.string_ ? value_.string_ : ""; + case booleanValue: + return value_.bool_ ? "true" : "false"; + case intValue: + case uintValue: + case realValue: + case arrayValue: + case objectValue: + JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return ""; // unreachable +} + +# ifdef JSON_USE_CPPTL +CppTL::ConstString +Value::asConstString() const +{ + return CppTL::ConstString( asString().c_str() ); +} +# endif + +Value::Int +Value::asInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + return value_.int_; + case uintValue: + JSON_ASSERT_MESSAGE( value_.uint_ < (unsigned)maxInt, "integer out of signed integer range" ); + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" ); + return Int( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_ASSERT_MESSAGE( false, "Type is not convertible to int" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + +Value::UInt +Value::asUInt() const +{ + switch ( type_ ) + { + case nullValue: + return 0; + case intValue: + JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" ); + return value_.int_; + case uintValue: + return value_.uint_; + case realValue: + JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" ); + return UInt( value_.real_ ); + case booleanValue: + return value_.bool_ ? 1 : 0; + case stringValue: + case arrayValue: + case objectValue: + JSON_ASSERT_MESSAGE( false, "Type is not convertible to uint" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + +double +Value::asDouble() const +{ + switch ( type_ ) + { + case nullValue: + return 0.0; + case intValue: + return value_.int_; + case uintValue: + return value_.uint_; + case realValue: + return value_.real_; + case booleanValue: + return value_.bool_ ? 1.0 : 0.0; + case stringValue: + case arrayValue: + case objectValue: + JSON_ASSERT_MESSAGE( false, "Type is not convertible to double" ); + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + +bool +Value::asBool() const +{ + switch ( type_ ) + { + case nullValue: + return false; + case intValue: + case uintValue: + return value_.int_ != 0; + case realValue: + return value_.real_ != 0.0; + case booleanValue: + return value_.bool_; + case stringValue: + return value_.string_ && value_.string_[0] != 0; + case arrayValue: + case objectValue: + return value_.map_->size() != 0; + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +bool +Value::isConvertibleTo( ValueType other ) const +{ + switch ( type_ ) + { + case nullValue: + return true; + case intValue: + return ( other == nullValue && value_.int_ == 0 ) + || other == intValue + || ( other == uintValue && value_.int_ >= 0 ) + || other == realValue + || other == stringValue + || other == booleanValue; + case uintValue: + return ( other == nullValue && value_.uint_ == 0 ) + || ( other == intValue && value_.uint_ <= (unsigned)maxInt ) + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case realValue: + return ( other == nullValue && value_.real_ == 0.0 ) + || ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt ) + || ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt ) + || other == realValue + || other == stringValue + || other == booleanValue; + case booleanValue: + return ( other == nullValue && value_.bool_ == false ) + || other == intValue + || other == uintValue + || other == realValue + || other == stringValue + || other == booleanValue; + case stringValue: + return other == stringValue + || ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) ); + case arrayValue: + return other == arrayValue + || ( other == nullValue && value_.map_->size() == 0 ); + case objectValue: + return other == objectValue + || ( other == nullValue && value_.map_->size() == 0 ); + default: + JSON_ASSERT_UNREACHABLE; + } + return false; // unreachable; +} + + +/// Number of values in array or object +Value::UInt +Value::size() const +{ + switch ( type_ ) + { + case nullValue: + case intValue: + case uintValue: + case realValue: + case booleanValue: + case stringValue: + return 0; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: // size of the array is highest index + 1 + if ( !value_.map_->empty() ) + { + ObjectValues::const_iterator itLast = value_.map_->end(); + --itLast; + return (*itLast).first.index()+1; + } + return 0; + case objectValue: + return Int( value_.map_->size() ); +#else + case arrayValue: + return Int( value_.array_->size() ); + case objectValue: + return Int( value_.map_->size() ); +#endif + default: + JSON_ASSERT_UNREACHABLE; + } + return 0; // unreachable; +} + + +bool +Value::empty() const +{ + if ( isNull() || isArray() || isObject() ) + return size() == 0u; + else + return false; +} + + +bool +Value::operator!() const +{ + return isNull(); +} + + +void +Value::clear() +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue ); + + switch ( type_ ) + { +#ifndef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + case objectValue: + value_.map_->clear(); + break; +#else + case arrayValue: + value_.array_->clear(); + break; + case objectValue: + value_.map_->clear(); + break; +#endif + default: + break; + } +} + +void +Value::resize( UInt newSize ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + UInt oldSize = size(); + if ( newSize == 0 ) + clear(); + else if ( newSize > oldSize ) + (*this)[ newSize - 1 ]; + else + { + for ( UInt index = newSize; index < oldSize; ++index ) + value_.map_->erase( index ); + assert( size() == newSize ); + } +#else + value_.array_->resize( newSize ); +#endif +} + + +Value & +Value::operator[]( UInt index ) +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + *this = Value( arrayValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::iterator it = value_.map_->lower_bound( key ); + if ( it != value_.map_->end() && (*it).first == key ) + return (*it).second; + + ObjectValues::value_type defaultValue( key, null ); + it = value_.map_->insert( it, defaultValue ); + return (*it).second; +#else + return value_.array_->resolveReference( index ); +#endif +} + + +const Value & +Value::operator[]( UInt index ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == arrayValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString key( index ); + ObjectValues::const_iterator it = value_.map_->find( key ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + Value *value = value_.array_->find( index ); + return value ? *value : null; +#endif +} + + +Value & +Value::operator[]( const char *key ) +{ + return resolveReference( key, false ); +} + + +Value & +Value::resolveReference( const char *key, + bool isStatic ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + *this = Value( objectValue ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, isStatic ? CZString::noDuplication + : CZString::duplicateOnCopy ); + ObjectValues::iterator it = value_.map_->lower_bound( actualKey ); + if ( it != value_.map_->end() && (*it).first == actualKey ) + return (*it).second; + + ObjectValues::value_type defaultValue( actualKey, null ); + it = value_.map_->insert( it, defaultValue ); + Value &value = (*it).second; + return value; +#else + return value_.map_->resolveReference( key, isStatic ); +#endif +} + + +Value +Value::get( UInt index, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[index]); + return value == &null ? defaultValue : *value; +} + + +bool +Value::isValidIndex( UInt index ) const +{ + return index < size(); +} + + + +const Value & +Value::operator[]( const char *key ) const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::const_iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + return (*it).second; +#else + const Value *value = value_.map_->find( key ); + return value ? *value : null; +#endif +} + + +Value & +Value::operator[]( const std::string &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const std::string &key ) const +{ + return (*this)[ key.c_str() ]; +} + +Value & +Value::operator[]( const StaticString &key ) +{ + return resolveReference( key, true ); +} + + +# ifdef JSON_USE_CPPTL +Value & +Value::operator[]( const CppTL::ConstString &key ) +{ + return (*this)[ key.c_str() ]; +} + + +const Value & +Value::operator[]( const CppTL::ConstString &key ) const +{ + return (*this)[ key.c_str() ]; +} +# endif + + +Value & +Value::append( const Value &value ) +{ + return (*this)[size()] = value; +} + + +Value +Value::get( const char *key, + const Value &defaultValue ) const +{ + const Value *value = &((*this)[key]); + return value == &null ? defaultValue : *value; +} + + +Value +Value::get( const std::string &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} + +Value +Value::removeMember( const char* key ) +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return null; +#ifndef JSON_VALUE_USE_INTERNAL_MAP + CZString actualKey( key, CZString::noDuplication ); + ObjectValues::iterator it = value_.map_->find( actualKey ); + if ( it == value_.map_->end() ) + return null; + Value old(it->second); + value_.map_->erase(it); + return old; +#else + Value *value = value_.map_->find( key ); + if (value){ + Value old(*value); + value_.map_.remove( key ); + return old; + } else { + return null; + } +#endif +} + +Value +Value::removeMember( const std::string &key ) +{ + return removeMember( key.c_str() ); +} + +# ifdef JSON_USE_CPPTL +Value +Value::get( const CppTL::ConstString &key, + const Value &defaultValue ) const +{ + return get( key.c_str(), defaultValue ); +} +# endif + +bool +Value::isMember( const char *key ) const +{ + const Value *value = &((*this)[key]); + return value != &null; +} + + +bool +Value::isMember( const std::string &key ) const +{ + return isMember( key.c_str() ); +} + + +# ifdef JSON_USE_CPPTL +bool +Value::isMember( const CppTL::ConstString &key ) const +{ + return isMember( key.c_str() ); +} +#endif + +Value::Members +Value::getMemberNames() const +{ + JSON_ASSERT( type_ == nullValue || type_ == objectValue ); + if ( type_ == nullValue ) + return Value::Members(); + Members members; + members.reserve( value_.map_->size() ); +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ObjectValues::const_iterator it = value_.map_->begin(); + ObjectValues::const_iterator itEnd = value_.map_->end(); + for ( ; it != itEnd; ++it ) + members.push_back( std::string( (*it).first.c_str() ) ); +#else + ValueInternalMap::IteratorState it; + ValueInternalMap::IteratorState itEnd; + value_.map_->makeBeginIterator( it ); + value_.map_->makeEndIterator( itEnd ); + for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) ) + members.push_back( std::string( ValueInternalMap::key( it ) ) ); +#endif + return members; +} +// +//# ifdef JSON_USE_CPPTL +//EnumMemberNames +//Value::enumMemberNames() const +//{ +// if ( type_ == objectValue ) +// { +// return CppTL::Enum::any( CppTL::Enum::transform( +// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ), +// MemberNamesTransform() ) ); +// } +// return EnumMemberNames(); +//} +// +// +//EnumValues +//Value::enumValues() const +//{ +// if ( type_ == objectValue || type_ == arrayValue ) +// return CppTL::Enum::anyValues( *(value_.map_), +// CppTL::Type<const Value &>() ); +// return EnumValues(); +//} +// +//# endif + + +bool +Value::isNull() const +{ + return type_ == nullValue; +} + + +bool +Value::isBool() const +{ + return type_ == booleanValue; +} + + +bool +Value::isInt() const +{ + return type_ == intValue; +} + + +bool +Value::isUInt() const +{ + return type_ == uintValue; +} + + +bool +Value::isIntegral() const +{ + return type_ == intValue + || type_ == uintValue + || type_ == booleanValue; +} + + +bool +Value::isDouble() const +{ + return type_ == realValue; +} + + +bool +Value::isNumeric() const +{ + return isIntegral() || isDouble(); +} + + +bool +Value::isString() const +{ + return type_ == stringValue; +} + + +bool +Value::isArray() const +{ + return type_ == nullValue || type_ == arrayValue; +} + + +bool +Value::isObject() const +{ + return type_ == nullValue || type_ == objectValue; +} + + +void +Value::setComment( const char *comment, + CommentPlacement placement ) +{ + if ( !comments_ ) + comments_ = new CommentInfo[numberOfCommentPlacement]; + comments_[placement].setComment( comment ); +} + + +void +Value::setComment( const std::string &comment, + CommentPlacement placement ) +{ + setComment( comment.c_str(), placement ); +} + + +bool +Value::hasComment( CommentPlacement placement ) const +{ + return comments_ != 0 && comments_[placement].comment_ != 0; +} + +std::string +Value::getComment( CommentPlacement placement ) const +{ + if ( hasComment(placement) ) + return comments_[placement].comment_; + return ""; +} + + +std::string +Value::toStyledString() const +{ + StyledWriter writer; + return writer.write( *this ); +} + + +Value::const_iterator +Value::begin() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + +Value::const_iterator +Value::end() const +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return const_iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return const_iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return const_iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return const_iterator(); +} + + +Value::iterator +Value::begin() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeBeginIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeBeginIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->begin() ); + break; +#endif + default: + break; + } + return iterator(); +} + +Value::iterator +Value::end() +{ + switch ( type_ ) + { +#ifdef JSON_VALUE_USE_INTERNAL_MAP + case arrayValue: + if ( value_.array_ ) + { + ValueInternalArray::IteratorState it; + value_.array_->makeEndIterator( it ); + return iterator( it ); + } + break; + case objectValue: + if ( value_.map_ ) + { + ValueInternalMap::IteratorState it; + value_.map_->makeEndIterator( it ); + return iterator( it ); + } + break; +#else + case arrayValue: + case objectValue: + if ( value_.map_ ) + return iterator( value_.map_->end() ); + break; +#endif + default: + break; + } + return iterator(); +} + + +// class PathArgument +// ////////////////////////////////////////////////////////////////// + +PathArgument::PathArgument() + : kind_( kindNone ) +{ +} + + +PathArgument::PathArgument( Value::UInt index ) + : index_( index ) + , kind_( kindIndex ) +{ +} + + +PathArgument::PathArgument( const char *key ) + : key_( key ) + , kind_( kindKey ) +{ +} + + +PathArgument::PathArgument( const std::string &key ) + : key_( key.c_str() ) + , kind_( kindKey ) +{ +} + +// class Path +// ////////////////////////////////////////////////////////////////// + +Path::Path( const std::string &path, + const PathArgument &a1, + const PathArgument &a2, + const PathArgument &a3, + const PathArgument &a4, + const PathArgument &a5 ) +{ + InArgs in; + in.push_back( &a1 ); + in.push_back( &a2 ); + in.push_back( &a3 ); + in.push_back( &a4 ); + in.push_back( &a5 ); + makePath( path, in ); +} + + +void +Path::makePath( const std::string &path, + const InArgs &in ) +{ + const char *current = path.c_str(); + const char *end = current + path.length(); + InArgs::const_iterator itInArg = in.begin(); + while ( current != end ) + { + if ( *current == '[' ) + { + ++current; + if ( *current == '%' ) + addPathInArg( path, in, itInArg, PathArgument::kindIndex ); + else + { + Value::UInt index = 0; + for ( ; current != end && *current >= '0' && *current <= '9'; ++current ) + index = index * 10 + Value::UInt(*current - '0'); + args_.push_back( index ); + } + if ( current == end || *current++ != ']' ) + invalidPath( path, int(current - path.c_str()) ); + } + else if ( *current == '%' ) + { + addPathInArg( path, in, itInArg, PathArgument::kindKey ); + ++current; + } + else if ( *current == '.' ) + { + ++current; + } + else + { + const char *beginName = current; + while ( current != end && !strchr( "[.", *current ) ) + ++current; + args_.push_back( std::string( beginName, current ) ); + } + } +} + + +void +Path::addPathInArg( const std::string &path, + const InArgs &in, + InArgs::const_iterator &itInArg, + PathArgument::Kind kind ) +{ + if ( itInArg == in.end() ) + { + // Error: missing argument %d + } + else if ( (*itInArg)->kind_ != kind ) + { + // Error: bad argument type + } + else + { + args_.push_back( **itInArg ); + } +} + + +void +Path::invalidPath( const std::string &path, + int location ) +{ + // Error: invalid path. +} + + +const Value & +Path::resolve( const Value &root ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + { + // Error: unable to resolve path (array value expected at position... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: unable to resolve path (object value expected at position...) + } + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + { + // Error: unable to resolve path (object has no member named '' at position...) + } + } + } + return *node; +} + + +Value +Path::resolve( const Value &root, + const Value &defaultValue ) const +{ + const Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() || node->isValidIndex( arg.index_ ) ) + return defaultValue; + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + return defaultValue; + node = &((*node)[arg.key_]); + if ( node == &Value::null ) + return defaultValue; + } + } + return *node; +} + + +Value & +Path::make( Value &root ) const +{ + Value *node = &root; + for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it ) + { + const PathArgument &arg = *it; + if ( arg.kind_ == PathArgument::kindIndex ) + { + if ( !node->isArray() ) + { + // Error: node is not an array at position ... + } + node = &((*node)[arg.index_]); + } + else if ( arg.kind_ == PathArgument::kindKey ) + { + if ( !node->isObject() ) + { + // Error: node is not an object at position... + } + node = &((*node)[arg.key_]); + } + } + return *node; +} + + +} // namespace Json diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_valueiterator.inl b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_valueiterator.inl new file mode 100644 index 00000000..736e260e --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_valueiterator.inl @@ -0,0 +1,292 @@ +// included by json_value.cpp +// everything is within Json namespace + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIteratorBase +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIteratorBase::ValueIteratorBase() +#ifndef JSON_VALUE_USE_INTERNAL_MAP + : current_() + , isNull_( true ) +{ +} +#else + : isArray_( true ) + , isNull_( true ) +{ + iterator_.array_ = ValueInternalArray::IteratorState(); +} +#endif + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIteratorBase::ValueIteratorBase( const Value::ObjectValues::iterator ¤t ) + : current_( current ) + , isNull_( false ) +{ +} +#else +ValueIteratorBase::ValueIteratorBase( const ValueInternalArray::IteratorState &state ) + : isArray_( true ) +{ + iterator_.array_ = state; +} + + +ValueIteratorBase::ValueIteratorBase( const ValueInternalMap::IteratorState &state ) + : isArray_( false ) +{ + iterator_.map_ = state; +} +#endif + +Value & +ValueIteratorBase::deref() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + return current_->second; +#else + if ( isArray_ ) + return ValueInternalArray::dereference( iterator_.array_ ); + return ValueInternalMap::value( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::increment() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + ++current_; +#else + if ( isArray_ ) + ValueInternalArray::increment( iterator_.array_ ); + ValueInternalMap::increment( iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::decrement() +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + --current_; +#else + if ( isArray_ ) + ValueInternalArray::decrement( iterator_.array_ ); + ValueInternalMap::decrement( iterator_.map_ ); +#endif +} + + +ValueIteratorBase::difference_type +ValueIteratorBase::computeDistance( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP +# ifdef JSON_USE_CPPTL_SMALLMAP + return current_ - other.current_; +# else + // Iterator for null value are initialized using the default + // constructor, which initialize current_ to the default + // std::map::iterator. As begin() and end() are two instance + // of the default std::map::iterator, they can not be compared. + // To allow this, we handle this comparison specifically. + if ( isNull_ && other.isNull_ ) + { + return 0; + } + + + // Usage of std::distance is not portable (does not compile with Sun Studio 12 RogueWave STL, + // which is the one used by default). + // Using a portable hand-made version for non random iterator instead: + // return difference_type( std::distance( current_, other.current_ ) ); + difference_type myDistance = 0; + for ( Value::ObjectValues::iterator it = current_; it != other.current_; ++it ) + { + ++myDistance; + } + return myDistance; +# endif +#else + if ( isArray_ ) + return ValueInternalArray::distance( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::distance( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +bool +ValueIteratorBase::isEqual( const SelfType &other ) const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + if ( isNull_ ) + { + return other.isNull_; + } + return current_ == other.current_; +#else + if ( isArray_ ) + return ValueInternalArray::equals( iterator_.array_, other.iterator_.array_ ); + return ValueInternalMap::equals( iterator_.map_, other.iterator_.map_ ); +#endif +} + + +void +ValueIteratorBase::copy( const SelfType &other ) +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + current_ = other.current_; +#else + if ( isArray_ ) + iterator_.array_ = other.iterator_.array_; + iterator_.map_ = other.iterator_.map_; +#endif +} + + +Value +ValueIteratorBase::key() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( czstring.c_str() ) + { + if ( czstring.isStaticString() ) + return Value( StaticString( czstring.c_str() ) ); + return Value( czstring.c_str() ); + } + return Value( czstring.index() ); +#else + if ( isArray_ ) + return Value( ValueInternalArray::indexOf( iterator_.array_ ) ); + bool isStatic; + const char *memberName = ValueInternalMap::key( iterator_.map_, isStatic ); + if ( isStatic ) + return Value( StaticString( memberName ) ); + return Value( memberName ); +#endif +} + + +UInt +ValueIteratorBase::index() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const Value::CZString czstring = (*current_).first; + if ( !czstring.c_str() ) + return czstring.index(); + return Value::UInt( -1 ); +#else + if ( isArray_ ) + return Value::UInt( ValueInternalArray::indexOf( iterator_.array_ ) ); + return Value::UInt( -1 ); +#endif +} + + +const char * +ValueIteratorBase::memberName() const +{ +#ifndef JSON_VALUE_USE_INTERNAL_MAP + const char *name = (*current_).first.c_str(); + return name ? name : ""; +#else + if ( !isArray_ ) + return ValueInternalMap::key( iterator_.map_ ); + return ""; +#endif +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueConstIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueConstIterator::ValueConstIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueConstIterator::ValueConstIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueConstIterator::ValueConstIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueConstIterator::ValueConstIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueConstIterator & +ValueConstIterator::operator =( const ValueIteratorBase &other ) +{ + copy( other ); + return *this; +} + + +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// class ValueIterator +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////// + +ValueIterator::ValueIterator() +{ +} + + +#ifndef JSON_VALUE_USE_INTERNAL_MAP +ValueIterator::ValueIterator( const Value::ObjectValues::iterator ¤t ) + : ValueIteratorBase( current ) +{ +} +#else +ValueIterator::ValueIterator( const ValueInternalArray::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} + +ValueIterator::ValueIterator( const ValueInternalMap::IteratorState &state ) + : ValueIteratorBase( state ) +{ +} +#endif + +ValueIterator::ValueIterator( const ValueConstIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator::ValueIterator( const ValueIterator &other ) + : ValueIteratorBase( other ) +{ +} + +ValueIterator & +ValueIterator::operator =( const SelfType &other ) +{ + copy( other ); + return *this; +} diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_writer.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_writer.cpp new file mode 100644 index 00000000..cdf4188f --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/json_writer.cpp @@ -0,0 +1,829 @@ +#include <json/writer.h> +#include <utility> +#include <assert.h> +#include <stdio.h> +#include <string.h> +#include <iostream> +#include <sstream> +#include <iomanip> + +#if _MSC_VER >= 1400 // VC++ 8.0 +#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated. +#endif + +namespace Json { + +static bool isControlCharacter(char ch) +{ + return ch > 0 && ch <= 0x1F; +} + +static bool containsControlCharacter( const char* str ) +{ + while ( *str ) + { + if ( isControlCharacter( *(str++) ) ) + return true; + } + return false; +} +static void uintToString( unsigned int value, + char *¤t ) +{ + *--current = 0; + do + { + *--current = (value % 10) + '0'; + value /= 10; + } + while ( value != 0 ); +} + +std::string valueToString( Int value ) +{ + char buffer[32]; + char *current = buffer + sizeof(buffer); + bool isNegative = value < 0; + if ( isNegative ) + value = -value; + uintToString( UInt(value), current ); + if ( isNegative ) + *--current = '-'; + assert( current >= buffer ); + return current; +} + + +std::string valueToString( UInt value ) +{ + char buffer[32]; + char *current = buffer + sizeof(buffer); + uintToString( value, current ); + assert( current >= buffer ); + return current; +} + +std::string valueToString( double value ) +{ + char buffer[32]; +#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning. + sprintf_s(buffer, sizeof(buffer), "%#.16g", value); +#else + sprintf(buffer, "%#.16g", value); +#endif + char* ch = buffer + strlen(buffer) - 1; + if (*ch != '0') return buffer; // nothing to truncate, so save time + while(ch > buffer && *ch == '0'){ + --ch; + } + char* last_nonzero = ch; + while(ch >= buffer){ + switch(*ch){ + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + --ch; + continue; + case '.': + // Truncate zeroes to save bytes in output, but keep one. + *(last_nonzero+2) = '\0'; + return buffer; + default: + return buffer; + } + } + return buffer; +} + + +std::string valueToString( bool value ) +{ + return value ? "true" : "false"; +} + +std::string valueToQuotedString( const char *value ) +{ + // Not sure how to handle unicode... + if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter( value )) + return std::string("\"") + value + "\""; + // We have to walk value and escape any special characters. + // Appending to std::string is not efficient, but this should be rare. + // (Note: forward slashes are *not* rare, but I am not escaping them.) + unsigned maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL + std::string result; + result.reserve(maxsize); // to avoid lots of mallocs + result += "\""; + for (const char* c=value; *c != 0; ++c) + { + switch(*c) + { + case '\"': + result += "\\\""; + break; + case '\\': + result += "\\\\"; + break; + case '\b': + result += "\\b"; + break; + case '\f': + result += "\\f"; + break; + case '\n': + result += "\\n"; + break; + case '\r': + result += "\\r"; + break; + case '\t': + result += "\\t"; + break; + //case '/': + // Even though \/ is considered a legal escape in JSON, a bare + // slash is also legal, so I see no reason to escape it. + // (I hope I am not misunderstanding something. + // blep notes: actually escaping \/ may be useful in javascript to avoid </ + // sequence. + // Should add a flag to allow this compatibility mode and prevent this + // sequence from occurring. + default: + if ( isControlCharacter( *c ) ) + { + std::ostringstream oss; + oss << "\\u" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << static_cast<int>(*c); + result += oss.str(); + } + else + { + result += *c; + } + break; + } + } + result += "\""; + return result; +} + +// Class Writer +// ////////////////////////////////////////////////////////////////// +Writer::~Writer() +{ +} + + +// Class FastWriter +// ////////////////////////////////////////////////////////////////// + +FastWriter::FastWriter() + : yamlCompatiblityEnabled_( false ) +{ +} + + +void +FastWriter::enableYAMLCompatibility() +{ + yamlCompatiblityEnabled_ = true; +} + + +std::string +FastWriter::write( const Value &root ) +{ + document_ = ""; + writeValue( root ); + document_ += "\n"; + return document_; +} + + +void +FastWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + document_ += "null"; + break; + case intValue: + document_ += valueToString( value.asInt() ); + break; + case uintValue: + document_ += valueToString( value.asUInt() ); + break; + case realValue: + document_ += valueToString( value.asDouble() ); + break; + case stringValue: + document_ += valueToQuotedString( value.asCString() ); + break; + case booleanValue: + document_ += valueToString( value.asBool() ); + break; + case arrayValue: + { + document_ += "["; + int size = value.size(); + for ( int index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ","; + writeValue( value[index] ); + } + document_ += "]"; + } + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + document_ += "{"; + for ( Value::Members::iterator it = members.begin(); + it != members.end(); + ++it ) + { + const std::string &name = *it; + if ( it != members.begin() ) + document_ += ","; + document_ += valueToQuotedString( name.c_str() ); + document_ += yamlCompatiblityEnabled_ ? ": " + : ":"; + writeValue( value[name] ); + } + document_ += "}"; + } + break; + } +} + + +// Class StyledWriter +// ////////////////////////////////////////////////////////////////// + +StyledWriter::StyledWriter() + : rightMargin_( 74 ) + , indentSize_( 3 ) +{ +} + + +std::string +StyledWriter::write( const Value &root ) +{ + document_ = ""; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + document_ += "\n"; + return document_; +} + + +void +StyledWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + while ( true ) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + document_ += " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + while ( true ) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + document_ += ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + document_ += "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + document_ += ", "; + document_ += childValues_[index]; + } + document_ += " ]"; + } + } +} + + +bool +StyledWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + document_ += value; +} + + +void +StyledWriter::writeIndent() +{ + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + document_ += '\n'; + } + document_ += indentString_; +} + + +void +StyledWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + document_ += value; +} + + +void +StyledWriter::indent() +{ + indentString_ += std::string( indentSize_, ' ' ); +} + + +void +StyledWriter::unindent() +{ + assert( int(indentString_.size()) >= indentSize_ ); + indentString_.resize( indentString_.size() - indentSize_ ); +} + + +void +StyledWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + document_ += normalizeEOL( root.getComment( commentBefore ) ); + document_ += "\n"; +} + + +void +StyledWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + document_ += " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + document_ += "\n"; + document_ += normalizeEOL( root.getComment( commentAfter ) ); + document_ += "\n"; + } +} + + +bool +StyledWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +// Class StyledStreamWriter +// ////////////////////////////////////////////////////////////////// + +StyledStreamWriter::StyledStreamWriter( std::string indentation ) + : document_(NULL) + , rightMargin_( 74 ) + , indentation_( indentation ) +{ +} + + +void +StyledStreamWriter::write( std::ostream &out, const Value &root ) +{ + document_ = &out; + addChildValues_ = false; + indentString_ = ""; + writeCommentBeforeValue( root ); + writeValue( root ); + writeCommentAfterValueOnSameLine( root ); + *document_ << "\n"; + document_ = NULL; // Forget the stream, for safety. +} + + +void +StyledStreamWriter::writeValue( const Value &value ) +{ + switch ( value.type() ) + { + case nullValue: + pushValue( "null" ); + break; + case intValue: + pushValue( valueToString( value.asInt() ) ); + break; + case uintValue: + pushValue( valueToString( value.asUInt() ) ); + break; + case realValue: + pushValue( valueToString( value.asDouble() ) ); + break; + case stringValue: + pushValue( valueToQuotedString( value.asCString() ) ); + break; + case booleanValue: + pushValue( valueToString( value.asBool() ) ); + break; + case arrayValue: + writeArrayValue( value); + break; + case objectValue: + { + Value::Members members( value.getMemberNames() ); + if ( members.empty() ) + pushValue( "{}" ); + else + { + writeWithIndent( "{" ); + indent(); + Value::Members::iterator it = members.begin(); + while ( true ) + { + const std::string &name = *it; + const Value &childValue = value[name]; + writeCommentBeforeValue( childValue ); + writeWithIndent( valueToQuotedString( name.c_str() ) ); + *document_ << " : "; + writeValue( childValue ); + if ( ++it == members.end() ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "}" ); + } + } + break; + } +} + + +void +StyledStreamWriter::writeArrayValue( const Value &value ) +{ + unsigned size = value.size(); + if ( size == 0 ) + pushValue( "[]" ); + else + { + bool isArrayMultiLine = isMultineArray( value ); + if ( isArrayMultiLine ) + { + writeWithIndent( "[" ); + indent(); + bool hasChildValue = !childValues_.empty(); + unsigned index =0; + while ( true ) + { + const Value &childValue = value[index]; + writeCommentBeforeValue( childValue ); + if ( hasChildValue ) + writeWithIndent( childValues_[index] ); + else + { + writeIndent(); + writeValue( childValue ); + } + if ( ++index == size ) + { + writeCommentAfterValueOnSameLine( childValue ); + break; + } + *document_ << ","; + writeCommentAfterValueOnSameLine( childValue ); + } + unindent(); + writeWithIndent( "]" ); + } + else // output on a single line + { + assert( childValues_.size() == size ); + *document_ << "[ "; + for ( unsigned index =0; index < size; ++index ) + { + if ( index > 0 ) + *document_ << ", "; + *document_ << childValues_[index]; + } + *document_ << " ]"; + } + } +} + + +bool +StyledStreamWriter::isMultineArray( const Value &value ) +{ + int size = value.size(); + bool isMultiLine = size*3 >= rightMargin_ ; + childValues_.clear(); + for ( int index =0; index < size && !isMultiLine; ++index ) + { + const Value &childValue = value[index]; + isMultiLine = isMultiLine || + ( (childValue.isArray() || childValue.isObject()) && + childValue.size() > 0 ); + } + if ( !isMultiLine ) // check if line length > max line length + { + childValues_.reserve( size ); + addChildValues_ = true; + int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' + for ( int index =0; index < size && !isMultiLine; ++index ) + { + writeValue( value[index] ); + lineLength += int( childValues_[index].length() ); + isMultiLine = isMultiLine && hasCommentForValue( value[index] ); + } + addChildValues_ = false; + isMultiLine = isMultiLine || lineLength >= rightMargin_; + } + return isMultiLine; +} + + +void +StyledStreamWriter::pushValue( const std::string &value ) +{ + if ( addChildValues_ ) + childValues_.push_back( value ); + else + *document_ << value; +} + + +void +StyledStreamWriter::writeIndent() +{ + /* + Some comments in this method would have been nice. ;-) + + if ( !document_.empty() ) + { + char last = document_[document_.length()-1]; + if ( last == ' ' ) // already indented + return; + if ( last != '\n' ) // Comments may add new-line + *document_ << '\n'; + } + */ + *document_ << '\n' << indentString_; +} + + +void +StyledStreamWriter::writeWithIndent( const std::string &value ) +{ + writeIndent(); + *document_ << value; +} + + +void +StyledStreamWriter::indent() +{ + indentString_ += indentation_; +} + + +void +StyledStreamWriter::unindent() +{ + assert( indentString_.size() >= indentation_.size() ); + indentString_.resize( indentString_.size() - indentation_.size() ); +} + + +void +StyledStreamWriter::writeCommentBeforeValue( const Value &root ) +{ + if ( !root.hasComment( commentBefore ) ) + return; + *document_ << normalizeEOL( root.getComment( commentBefore ) ); + *document_ << "\n"; +} + + +void +StyledStreamWriter::writeCommentAfterValueOnSameLine( const Value &root ) +{ + if ( root.hasComment( commentAfterOnSameLine ) ) + *document_ << " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) ); + + if ( root.hasComment( commentAfter ) ) + { + *document_ << "\n"; + *document_ << normalizeEOL( root.getComment( commentAfter ) ); + *document_ << "\n"; + } +} + + +bool +StyledStreamWriter::hasCommentForValue( const Value &value ) +{ + return value.hasComment( commentBefore ) + || value.hasComment( commentAfterOnSameLine ) + || value.hasComment( commentAfter ); +} + + +std::string +StyledStreamWriter::normalizeEOL( const std::string &text ) +{ + std::string normalized; + normalized.reserve( text.length() ); + const char *begin = text.c_str(); + const char *end = begin + text.length(); + const char *current = begin; + while ( current != end ) + { + char c = *current++; + if ( c == '\r' ) // mac or dos EOL + { + if ( *current == '\n' ) // convert dos EOL + ++current; + normalized += '\n'; + } + else // handle unix EOL & other char + normalized += c; + } + return normalized; +} + + +std::ostream& operator<<( std::ostream &sout, const Value &root ) +{ + Json::StyledStreamWriter writer; + writer.write(sout, root); + return sout; +} + + +} // namespace Json diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/plugin.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/plugin.cpp new file mode 100644 index 00000000..6906275e --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/plugin.cpp @@ -0,0 +1,320 @@ +#include "plugin.h" +#include "tokenizer.h" + +#ifdef _WINDOWS +#include <windows.h> +BOOL APIENTRY DllMain( HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved ) +{ + return TRUE; +} +#else +#include <errno.h> +#include <string.h> + +extern int errno; +#endif + +SendPluginEv SendPluginEvent; + +string g_GetSysErrMsg( void ) +{ + string strError = "Unknown"; + // Problem loading +#ifdef _WINDOWS + int nErrorCode = GetLastError(); + LPTSTR s; + if ( ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, nErrorCode, 0, ( LPTSTR ) &s, 0, NULL ) ) + { + strError = s; + } + else + { + char szBuf[ 20 ]; + _snprintf_s( szBuf, _countof(szBuf), 19, "%d", nErrorCode ); + strError = szBuf; + } +#else + char szError[80]; + if ( strerror_r( errno, szError, sizeof(szError) ) ) + { + strError = "no description found"; + } + else + { + strError = szError; + } +#endif + return strError; +} + +void g_sleep( unsigned int mseconds ) +{ +#ifdef _WINDOWS + Sleep( mseconds ); +#else + usleep( mseconds * 1000 ); +#endif +} + +string& g_trim( string& str ) +{ + // Whitespace characters + char whspc[] = " \t\r\n\v\f"; + + // Whack off first part + size_t pos = str.find_first_not_of( whspc ); + + if ( pos != string::npos ) + str.replace( 0, pos, "" ); + + // Whack off trailing stuff + pos = str.find_last_not_of( whspc ); + + if ( pos != string::npos ) + str.replace( pos + 1, str.length() - pos, "" ); + + return str; +} + +void g_tokenize( const string& str, const string& delimiters, vector<string>& tokens ) +{ + tokenize( str, tokens, delimiters ); +} + +char* SetEventFunc( SendPluginEv funcPtr ) +{ + static char * szObjList = onGetObjList(); + SendPluginEvent = funcPtr; + return szObjList; +} + + +const int nMAXSIZE = 512; +char* g_pszRetVal = NULL; + +//----------------------------------------------------------- +// Map from an object Id to an object instance +//----------------------------------------------------------- +typedef std::map<string, JSExt*> StringToJExt_T; + +//----------------------------------------------------------- +// Map from a browser context to an id mapping +//----------------------------------------------------------- +typedef std::map<void*, StringToJExt_T*> VoidToMap_T; + +VoidToMap_T g_context2Map; + +class GlobalSharedModule +{ + +public: + GlobalSharedModule( void ) + { + g_pszRetVal = new char[ nMAXSIZE ]; + } + + ~GlobalSharedModule() + { + delete [] g_pszRetVal; + + VoidToMap_T::iterator posMaps; + + for ( posMaps = g_context2Map.begin(); posMaps != g_context2Map.end(); ++posMaps ) + { + StringToJExt_T& id2Obj = *posMaps->second; + StringToJExt_T::iterator posMap; + + for ( posMap = id2Obj.begin(); posMap != id2Obj.end(); ++posMap ) + { + JSExt* pJSExt = posMap->second; + + if ( pJSExt->CanDelete() ) + { + delete pJSExt; + } + } + + id2Obj.erase( id2Obj.begin(), id2Obj.end() ); + } + + g_context2Map.erase( g_context2Map.begin(), g_context2Map.end() ); + } +}; + +GlobalSharedModule g_sharedModule; + +char* g_str2global( const string& strRetVal ) +{ + int nLen = strRetVal.size(); + + if ( nLen >= nMAXSIZE ) + { + delete [] g_pszRetVal; + g_pszRetVal = new char[ nLen + 1 ]; + } + + else + { + // To minimaize the number of memory reallocations, the assumption + // is that in most times this will be the case + delete [] g_pszRetVal; + g_pszRetVal = new char[ nMAXSIZE ]; + } + + strcpy( g_pszRetVal, strRetVal.c_str() ); + return g_pszRetVal; +} + +bool g_unregisterObject( const string& strObjId, void* pContext ) +{ + // Called by the plugin extension implementation + // if the extension handles the deletion of its object + + StringToJExt_T * pID2Obj = NULL; + + VoidToMap_T::iterator iter = g_context2Map.find( pContext ); + + if ( iter != g_context2Map.end() ) + { + pID2Obj = iter->second; + } + else + { + return false; + } + + StringToJExt_T& mapID2Obj = *pID2Obj; + + StringToJExt_T::iterator r = mapID2Obj.find( strObjId ); + + if ( r == mapID2Obj.end() ) + { + return false; + } + + mapID2Obj.erase( strObjId ); + return true; +} + +char* InvokeFunction( const char* szCommand, void* pContext ) +{ + StringToJExt_T * pID2Obj = NULL; + + VoidToMap_T::iterator iter = g_context2Map.find( pContext ); + + if ( iter != g_context2Map.end() ) + { + pID2Obj = iter->second; + } + else + { + pID2Obj = new StringToJExt_T; + g_context2Map[ pContext ] = pID2Obj; + } + + StringToJExt_T& mapID2Obj = *pID2Obj; + + string strFullCommand = szCommand; + vector<string> arParams; + g_tokenize( strFullCommand, " ", arParams ); + string strCommand = arParams[ 0 ]; + string strRetVal = szERROR; + + if ( strCommand == szCREATE ) + { + string strClassName = arParams[ 1 ]; + string strObjId = arParams[ 2 ]; + + StringToJExt_T::iterator r = mapID2Obj.find( strObjId ); + + if ( r != mapID2Obj.end() ) + { + strRetVal += strObjId; + strRetVal += " :Object already exists."; + return g_str2global( strRetVal ); + } + + JSExt* pJSExt = onCreateObject( strClassName, strObjId ); + + if ( pJSExt == NULL ) + { + strRetVal += strObjId; + strRetVal += " :Unknown object type "; + strRetVal += strClassName; + return g_str2global( strRetVal ); + } + + pJSExt->m_pContext = pContext; + mapID2Obj[ strObjId ] = pJSExt; + + strRetVal = szOK; + strRetVal += strObjId; + return g_str2global( strRetVal ); + } + else + if ( strCommand == szINVOKE ) + { + string strObjId = arParams[ 1 ]; + string strMethod = arParams[ 2 ]; + + StringToJExt_T::iterator r = mapID2Obj.find( strObjId ); + + if ( r == mapID2Obj.end() ) + { + strRetVal += strObjId; + strRetVal += " :No object found for id."; + return g_str2global( strRetVal ); + } + + JSExt* pJSExt = r->second; + + size_t nLoc = strFullCommand.find( strObjId ); + + if ( nLoc == string::npos ) + { + strRetVal += strObjId; + strRetVal += " :Internal InvokeMethod error."; + return g_str2global( strRetVal ); + } + + if ( strMethod == szDISPOSE ) + { + StringToJExt_T::iterator r = mapID2Obj.find( strObjId ); + + if ( r == mapID2Obj.end() ) + { + strRetVal = szERROR; + strRetVal += strObjId; + return g_str2global( strRetVal ); + } + + JSExt * pJSExt = mapID2Obj[ strObjId ]; + + if ( pJSExt->CanDelete() ) + { + delete pJSExt; + } + + mapID2Obj.erase( strObjId ); + strRetVal = szOK; + strRetVal += strObjId; + return g_str2global( strRetVal ); + } + + size_t nSuffixLoc = nLoc + strObjId.size(); + string strInvoke = strFullCommand.substr( nSuffixLoc ); + strInvoke = g_trim( strInvoke ); + strRetVal = pJSExt->InvokeMethod( strInvoke ); + return g_str2global( strRetVal ); + } + + strRetVal += " :Unknown command "; + strRetVal += strCommand; + return g_str2global( strRetVal ); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/plugin.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/plugin.h new file mode 100644 index 00000000..4ef71169 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/plugin.h @@ -0,0 +1,70 @@ +#ifndef _PLUGIN_H +#define _PLUGIN_H + +#include <map> +#include <string> +#include <vector> +#include <unistd.h> +//#include "tokenizer.h" + +using namespace std; + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +//%% Functions exported by this DLL +//%% Should always be only SetEventFunc and InvokeFunction +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// g++ requires extern "C" otherwise the names of SetEventFunc and InvokeFunction +// are mangled C++ style. MS Visual Studio doesn't seem to care though. +extern "C" +{ + typedef void (*SendPluginEv)( const char* szEvent, void* pContext ); + char* SetEventFunc(SendPluginEv funcPtr); + char* InvokeFunction( const char* szCommand, void* pContext ); +} + +// JNEXT Framework function of the form: +// typedef void (*SendPluginEv)( const char* szEvent ); +// used to notify JavaScript of an asynchronous event +extern SendPluginEv SendPluginEvent; + +///////////////////////////////////////////////////////////////////////// +// Constants and methods common to all JNEXT extensions types +///////////////////////////////////////////////////////////////////////// +#define szERROR "Error " +#define szOK "Ok " + +#define szDISPOSE "Dispose" +#define szINVOKE "InvokeMethod" +#define szCREATE "CreateObj" + +///////////////////////////////////////////////////////////////////////// +// Utility functions +///////////////////////////////////////////////////////////////////////// +string& g_trim( string& str ); +void g_tokenize(const string& str,const string& delimiters, vector<string>& tokens); +char* g_str2static( const string& strRetVal ); +void g_sleep( unsigned int mseconds ); +bool g_unregisterObject( const string& strObjId, void* pContext ); + + +///////////////////////////////////////////////////////////////////////// +// Abstract extension object +///////////////////////////////////////////////////////////////////////// +class JSExt +{ +public: + virtual ~JSExt() {}; + virtual string InvokeMethod( const string& strCommand ) = 0; + virtual bool CanDelete( void ) = 0; + virtual void TryDelete( void ) {} +public: + void* m_pContext; +}; + +///////////////////////////////////////////////////////////////////////// +// Callback functions to be implemented by the plugin implementation +///////////////////////////////////////////////////////////////////////// +extern char* onGetObjList( void ); +extern JSExt* onCreateObject( const string& strClassName, const string& strObjId ); + +#endif diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/tokenizer.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/tokenizer.cpp new file mode 100644 index 00000000..4a39573b --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/tokenizer.cpp @@ -0,0 +1,222 @@ +/************************************************************************ +The zlib/libpng License + +Copyright (c) 2006 Joerg Wiedenmann + +This software is provided 'as-is', without any express or implied warranty. +In no event will the authors be held liable for any damages arising from +the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; +you must not claim that you wrote the original software. +If you use this software in a product, an acknowledgment +in the product documentation would be appreciated but is +not required. + +2. Altered source versions must be plainly marked as such, +and must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + +***********************************************************************/ + +/******************************************************************** + created: 2006-01-28 + filename: tokenizer.cpp + author: Jörg Wiedenmann + + purpose: A tokenizer function which provides a very + customizable way of breaking up strings. + + history: 2006-01-28, Original version + 2006-03-04, Fixed a small parsing bug, thanks Elias. +*********************************************************************/ + +#include "tokenizer.h" + +using namespace std; + +void tokenize ( const string& str, vector<string>& result, + const string& delimiters, const string& delimiters_preserve, + const string& quote, const string& esc ) +{ + // clear the vector + if ( false == result.empty() ) + { + result.clear(); + } + + string::size_type pos = 0; // the current position (char) in the string + char ch = 0; // buffer for the current character + char delimiter = 0; // the buffer for the delimiter char which + // will be added to the tokens if the delimiter + // is preserved + char current_quote = 0; // the char of the current open quote + bool quoted = false; // indicator if there is an open quote + string token; // string buffer for the token + bool token_complete = false; // indicates if the current token is + // read to be added to the result vector + string::size_type len = str.length(); // length of the input-string + + // for every char in the input-string + while ( len > pos ) + { + // get the character of the string and reset the delimiter buffer + ch = str.at(pos); + delimiter = 0; + + // assume ch isn't a delimiter + bool add_char = true; + + // check ... + + // ... if the delimiter is an escaped character + bool escaped = false; // indicates if the next char is protected + if ( false == esc.empty() ) // check if esc-chars are provided + { + if ( string::npos != esc.find_first_of(ch) ) + { + // get the escaped char + ++pos; + if ( pos < len ) // if there are more chars left + { + // get the next one + ch = str.at(pos); + + // add the escaped character to the token + add_char = true; + } + else // cannot get any more characters + { + // don't add the esc-char + add_char = false; + } + + // ignore the remaining delimiter checks + escaped = true; + } + } + + // ... if the delimiter is a quote + if ( false == quote.empty() && false == escaped ) + { + // if quote chars are provided and the char isn't protected + if ( string::npos != quote.find_first_of(ch) ) + { + // if not quoted, set state to open quote and set + // the quote character + if ( false == quoted ) + { + quoted = true; + current_quote = ch; + + // don't add the quote-char to the token + add_char = false; + } + else // if quote is open already + { + // check if it is the matching character to close it + if ( current_quote == ch ) + { + // close quote and reset the quote character + quoted = false; + current_quote = 0; + + // don't add the quote-char to the token + add_char = false; + } + } // else + } + } + + // ... if the delimiter isn't preserved + if ( false == delimiters.empty() && false == escaped && + false == quoted ) + { + // if a delimiter is provided and the char isn't protected by + // quote or escape char + if ( string::npos != delimiters.find_first_of(ch) ) + { + // if ch is a delimiter and the token string isn't empty + // the token is complete + if ( false == token.empty() ) // BUGFIX: 2006-03-04 + { + token_complete = true; + } + + // don't add the delimiter to the token + add_char = false; + } + } + + // ... if the delimiter is preserved - add it as a token + bool add_delimiter = false; + if ( false == delimiters_preserve.empty() && false == escaped && + false == quoted ) + { + // if a delimiter which will be preserved is provided and the + // char isn't protected by quote or escape char + if ( string::npos != delimiters_preserve.find_first_of(ch) ) + { + // if ch is a delimiter and the token string isn't empty + // the token is complete + if ( false == token.empty() ) // BUGFIX: 2006-03-04 + { + token_complete = true; + } + + // don't add the delimiter to the token + add_char = false; + + // add the delimiter + delimiter = ch; + add_delimiter = true; + } + } + + + // add the character to the token + if ( true == add_char ) + { + // add the current char + token.push_back( ch ); + } + + // add the token if it is complete + if ( true == token_complete && false == token.empty() ) + { + // add the token string + result.push_back( token ); + + // clear the contents + token.clear(); + + // build the next token + token_complete = false; + } + + // add the delimiter + if ( true == add_delimiter ) + { + // the next token is the delimiter + string delim_token; + delim_token.push_back( delimiter ); + result.push_back( delim_token ); + + // REMOVED: 2006-03-04, Bugfix + } + + // repeat for the next character + ++pos; + } // while + + // add the final token + if ( false == token.empty() ) + { + result.push_back( token ); + } +} diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/tokenizer.h b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/tokenizer.h new file mode 100644 index 00000000..75f567ce --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/public/tokenizer.h @@ -0,0 +1,55 @@ +/************************************************************************ +The zlib/libpng License + +Copyright (c) 2006 Joerg Wiedenmann + +This software is provided 'as-is', without any express or implied warranty. +In no event will the authors be held liable for any damages arising from +the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; + you must not claim that you wrote the original software. + If you use this software in a product, an acknowledgment + in the product documentation would be appreciated but is + not required. + +2. Altered source versions must be plainly marked as such, + and must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + +***********************************************************************/ + +/******************************************************************** + created: 2006-01-28 + filename: tokenizer.cpp + author: Jörg Wiedenmann + + purpose: A tokenizer function which provides a very + customizable way of breaking up strings. +*********************************************************************/ + +#include <vector> +#include <string> +using namespace std; + +// Function to break up a string into tokens +// +// Parameters: +//----------- +// str = the input string that will be tokenized +// result = the tokens for str +// delimiters = the delimiter characters +// delimiters preserve = same as above, but the delimiter characters +// will be put into the result as a token +// quote = characters to protect the enclosed characters +// esc = characters to protect a single character +// + +void tokenize ( const string& str, vector<string>& result, + const string& delimiters, const string& delimiters_preserve = "", + const string& quote = "\"", const string& esc = "\\" ); diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/Logger.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/Logger.cpp new file mode 100644 index 00000000..57b7075e --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/Logger.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2013 BlackBerry Limited + * + * Licensed 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 "Logger.hpp" +#include "keyboard_js.hpp" +#include <slog2.h> + +namespace webworks { + +Logger::Logger(const char* name, Keyboard_JS *parent): m_pParent(parent) { + buffer_config.buffer_set_name = name; + buffer_config.num_buffers = 2; + buffer_config.verbosity_level = SLOG2_DEBUG1; + + /* Configure the first buffer, using 7 x 4KB pages. This larger buffer will be used for + very chatty logging. Our goal is to have 30-60 seconds of history at any given time, + so we will want to log at a rate of around one log line with a string of 16 bytes + long every 150 milliseconds. + */ + + buffer_config.buffer_config[0].buffer_name = "low_priority"; + buffer_config.buffer_config[0].num_pages = 7; + + /* Configure the second buffer, which we will use for high level info logging that is very + infrequent, but we want a longer history (hours or maybe even over a day or two). This + buffer uses 1 x 4KB. + */ + + buffer_config.buffer_config[1].buffer_name = "high_priority"; + buffer_config.buffer_config[1].num_pages = 1; + + /* Register the buffer set. */ + + if( -1 == slog2_register( &buffer_config, buffer_handle, 0 ) ) { + fprintf( stderr, "Error registering slogger2 buffer!\n" ); + } else { + info("Created slogger2 buffers"); + } + +} + +Logger::~Logger() { + critical("slogger2 buffers reset"); + slog2_reset(); +} + +int Logger::log(slog2_buffer_t buffer, _Uint8t severity, const char* message) { + return slog2c(buffer, 0, severity, message); +} + +int Logger::debug(const char* message) { + return log(lowPriorityBuffer(), SLOG2_DEBUG1, message); +} + +int Logger::info(const char* message) { + return log(lowPriorityBuffer(), SLOG2_INFO, message); +} + +int Logger::notice(const char* message) { + return log(lowPriorityBuffer(), SLOG2_NOTICE, message); +} + +int Logger::warn(const char* message) { + return log(lowPriorityBuffer(), SLOG2_WARNING, message); +} + +int Logger::error(const char* message) { + return log(hiPriorityBuffer(), SLOG2_ERROR, message); +} + +int Logger::critical(const char* message) { + return log(hiPriorityBuffer(), SLOG2_CRITICAL, message); +} + +int Logger::setVerbosity(_Uint8t verbosity) { + return slog2_set_verbosity(buffer_handle[0], verbosity); +} + +_Uint8t Logger::getVerbosity() { + return slog2_get_verbosity(buffer_handle[0]); +} + +slog2_buffer_t Logger::hiPriorityBuffer() { + return buffer_handle[1]; +} + +slog2_buffer_t Logger::lowPriorityBuffer() { + return buffer_handle[0]; +} + +} /* namespace webworks */ diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/Logger.hpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/Logger.hpp new file mode 100644 index 00000000..ca379ca7 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/Logger.hpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013 BlackBerry Limited + * + * Licensed 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 LOGGER_HPP_ +#define LOGGER_HPP_ + +#include <string> +#include <slog2.h> + +class Keyboard_JS; + +namespace webworks { + +class Logger { +public: + explicit Logger(const char* name, Keyboard_JS *parent = NULL); + virtual ~Logger(); + int debug(const char* message); + int info(const char* message); + int notice(const char* message); + int warn(const char* message); + int error(const char* message); + int critical(const char* message); + int setVerbosity(_Uint8t verbosity); + _Uint8t getVerbosity(); + slog2_buffer_t hiPriorityBuffer(); + slog2_buffer_t lowPriorityBuffer(); +private: + Keyboard_JS *m_pParent; + slog2_buffer_set_config_t buffer_config; + slog2_buffer_t buffer_handle[2]; + int log(slog2_buffer_t buffer, _Uint8t severity, const char* message); +}; + +} /* namespace webworks */ +#endif /* LOGGER_HPP_ */ diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_js.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_js.cpp new file mode 100644 index 00000000..64250a14 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_js.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2013 BlackBerry Limited + * + * Licensed 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 <string> +#include "../public/tokenizer.h" +#include "keyboard_js.hpp" +#include "keyboard_ndk.hpp" +#include <sstream> + +using namespace std; + +/** + * Default constructor. + */ +Keyboard_JS::Keyboard_JS(const std::string& id) : + m_id(id) { + m_pLogger = new webworks::Logger("Keyboard_JS", this); + m_pKeyboardController = new webworks::Keyboard_NDK(this); + + +} + +/** + * Keyboard_JS destructor. + */ +Keyboard_JS::~Keyboard_JS() { + if (m_pKeyboardController) + delete m_pKeyboardController; + if (m_pLogger) + delete m_pLogger; +} + +webworks::Logger* Keyboard_JS::getLog() { + return m_pLogger; +} + +/** + * This method returns the list of objects implemented by this native + * extension. + */ +char* onGetObjList() { + static char name[] = "Keyboard_JS"; + return name; +} + +/** + * This method is used by JNext to instantiate the Keyboard_JS object when + * an object is created on the JavaScript server side. + */ +JSExt* onCreateObject(const string& className, const string& id) { + if (className == "Keyboard_JS") { + return new Keyboard_JS(id); + } + + return NULL; +} + +/** + * Method used by JNext to determine if the object can be deleted. + */ +bool Keyboard_JS::CanDelete() { + return true; +} + +/** + * It will be called from JNext JavaScript side with passed string. + * This method implements the interface for the JavaScript to native binding + * for invoking native code. This method is triggered when JNext.invoke is + * called on the JavaScript side with this native objects id. + */ +string Keyboard_JS::InvokeMethod(const string& command) { + // format must be: "command callbackId params" + size_t commandIndex = command.find_first_of(" "); + std::string strCommand = command.substr(0, commandIndex); + size_t callbackIndex = command.find_first_of(" ", commandIndex + 1); + std::string callbackId = command.substr(commandIndex + 1, callbackIndex - commandIndex - 1); + std::string arg = command.substr(callbackIndex + 1, command.length()); + + // based on the command given, run the appropriate method in keyboard_ndk.cpp + if (strCommand == "showKeyboard") { + m_pKeyboardController->callKeyboardEmail(); + return "Show Keyboard"; + } else if (strCommand == "closeKeyboard") { + m_pKeyboardController->cancelKeyboard(); + return "Cancel Keyboard"; + } + else if(strCommand == "startService"){ + m_pKeyboardController->keyboardStartThread(); + return "Starting Service"; + } + + strCommand.append(";"); + strCommand.append(command); + return strCommand; +} + +// Notifies JavaScript of an event +void Keyboard_JS::NotifyEvent(const std::string& event) { + std::string eventString = m_id + " "; + eventString.append(event); + SendPluginEvent(eventString.c_str(), m_pContext); + +} + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_js.hpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_js.hpp new file mode 100644 index 00000000..1ed3bb78 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_js.hpp @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2013 BlackBerry Limited +* +* Licensed 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 Keyboard_JS_HPP_ +#define Keyboard_JS_HPP_ + +#include <string> +#include "../public/plugin.h" +#include "keyboard_ndk.hpp" +#include "Logger.hpp" + + +class Keyboard_JS: public JSExt { + +public: + explicit Keyboard_JS(const std::string& id); + virtual ~Keyboard_JS(); + virtual bool CanDelete(); + virtual std::string InvokeMethod(const std::string& command); + void NotifyEvent(const std::string& event); + webworks::Logger* getLog(); +private: + std::string m_id; + webworks::Keyboard_NDK *m_pKeyboardController; + webworks::Logger *m_pLogger; + +}; + +#endif /* Keyboard_JS_HPP_ */ diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_ndk.cpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_ndk.cpp new file mode 100644 index 00000000..26b2e39a --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_ndk.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2013 BlackBerry Limited + * + * Licensed 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 <string> +#include <sstream> +#include <json/reader.h> +#include <json/writer.h> +#include <pthread.h> +#include "keyboard_ndk.hpp" +#include "keyboard_js.hpp" +#include <QtCore> +namespace webworks { + +Keyboard_NDK::Keyboard_NDK(Keyboard_JS *parent): + m_pParent(parent), + keyboardProperty(50), + keyboardThreadCount(1), + threadHalt(true), + m_thread(0) { + pthread_cond_t cond = PTHREAD_COND_INITIALIZER; + pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + bps_initialize(); + + virtualkeyboard_request_events(0); + + virtualkeyboard_change_options(VIRTUALKEYBOARD_LAYOUT_EMAIL,VIRTUALKEYBOARD_ENTER_DEFAULT); + + m_pParent->getLog()->info("Keyboard Created"); + + +} + + +Keyboard_NDK::~Keyboard_NDK() { + //bps_shutdown(); +} + + +// Loops and runs the callback method +void* KeyboardThread(void* parent) { + Keyboard_NDK *pParent = static_cast<Keyboard_NDK *>(parent); + + sleep(1); + + // 1. Start the library + bps_initialize(); + + // 2. Request events to flow into the event queue + virtualkeyboard_request_events(0); + + sleep(3); + // 3. Use any service at any time + //virtualkeyboard_show(); // Show the virtual keyboard + + // 4. Listen for events + for (;;) { + // get an event + bps_event_t *event; + bps_get_event(&event, -1); // blocking + + // handle the event + pParent->event(event); + } + return NULL; +} + +// Starts the thread and returns a message on status +std::string Keyboard_NDK::keyboardStartThread() { + m_pParent->NotifyEvent("Teste"); + if (!m_thread) { + m_pParent->NotifyEvent("Teste"); + int rc; + rc = pthread_mutex_lock(&mutex); + threadHalt = false; + rc = pthread_cond_signal(&cond); + rc = pthread_mutex_unlock(&mutex); + + pthread_attr_t thread_attr; + pthread_attr_init(&thread_attr); + pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); + + pthread_create(&m_thread, &thread_attr, KeyboardThread, + static_cast<void *>(this)); + pthread_attr_destroy(&thread_attr); + //threadCallbackId = callbackId; + m_pParent->getLog()->info("Thread Started"); + return "Thread Started"; + } else { + m_pParent->getLog()->warn("Thread Started but already running"); + return "Thread Running"; + } +} + + +void Keyboard_NDK::event(bps_event_t *event) { + Json::FastWriter writer; + Json::Value root; + root["threadCount"] = "10"; + int domain = bps_event_get_domain(event); + if (domain == virtualkeyboard_get_domain()) { + int code = bps_event_get_code(event); + int a; + std::string str; + std::string eventString; + std::ostringstream strs; + switch(code) { + case VIRTUALKEYBOARD_EVENT_VISIBLE: + eventString = "native.keyboardshow"; + eventString.append(" "); + virtualkeyboard_get_height(&a) ; + strs << a; + str = strs.str(); + eventString.append("{\"keyboardHeight\":\""+str+"\"}"); + m_pParent->NotifyEvent(eventString); + + break; + case VIRTUALKEYBOARD_EVENT_HIDDEN: + + m_pParent->NotifyEvent("native.keyboardhide"); + break; + } + } + +} +void Keyboard_NDK::callKeyboardEmail(){ + virtualkeyboard_change_options(VIRTUALKEYBOARD_LAYOUT_EMAIL,VIRTUALKEYBOARD_ENTER_SEND); + virtualkeyboard_show(); +} + +void Keyboard_NDK::callKeyboardNumber(){ + + virtualkeyboard_change_options(VIRTUALKEYBOARD_LAYOUT_NUMBER,VIRTUALKEYBOARD_ENTER_SEND); + virtualkeyboard_show(); +} +void Keyboard_NDK::cancelKeyboard(){ + virtualkeyboard_hide(); +} + + + + +} diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_ndk.hpp b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_ndk.hpp new file mode 100644 index 00000000..01062274 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/blackberry10/native/src/keyboard_ndk.hpp @@ -0,0 +1,71 @@ +/* +* Copyright (c) 2013 BlackBerry Limited +* +* Licensed 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 Keyboard_NDK_HPP_ +#define Keyboard_NDK_HPP_ + +#include <string> +#include <pthread.h> +#include <bb/AbstractBpsEventHandler> +#include <bps/bps.h> +#include<bps/netstatus.h> +#include<bps/locale.h> +#include<bps/virtualkeyboard.h> +#include<bps/navigator.h> +#include <bps/event.h> +#include <string> +#include <sstream> + +class Keyboard_JS; + +namespace webworks { + +class Keyboard_NDK { +public: + explicit Keyboard_NDK(Keyboard_JS *parent = NULL); + virtual ~Keyboard_NDK(); + virtual void event(bps_event_t *event); + + void callKeyboardEmail(); // Method Calls the Keyboard style Email (default) + + void callKeyboardNumber(); // Method Calls the Keyboard style number + + void cancelKeyboard(); // Method cancel the keyboard + + std::string keyboardStartThread(); + + + + + + + +private: + + Keyboard_JS *m_pParent; + int keyboardProperty; + int keyboardThreadCount; + bool threadHalt; + std::string threadCallbackId; + pthread_t m_thread; + pthread_cond_t cond; + pthread_mutex_t mutex; + +}; + +} // namespace webworks + +#endif /* Keyboard_NDK_HPP_ */ diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/ios/IonicKeyboard.h b/StoneIsland/plugins/com.ionic.keyboard/src/ios/IonicKeyboard.h new file mode 100644 index 00000000..b54f430d --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/ios/IonicKeyboard.h @@ -0,0 +1,13 @@ +#import <Cordova/CDVPlugin.h> + +@interface IonicKeyboard : CDVPlugin <UIScrollViewDelegate> { + @protected + id _keyboardShowObserver, _keyboardHideObserver; +} + +@property (readwrite, assign) BOOL hideKeyboardAccessoryBar; +@property (readwrite, assign) BOOL disableScroll; +//@property (readwrite, assign) BOOL styleDark; + +@end + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/ios/IonicKeyboard.m b/StoneIsland/plugins/com.ionic.keyboard/src/ios/IonicKeyboard.m new file mode 100644 index 00000000..045cc65f --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/ios/IonicKeyboard.m @@ -0,0 +1,160 @@ +#import "IonicKeyboard.h" +#import "UIWebViewExtension.h" +#import <Cordova/CDVAvailability.h> + +@implementation IonicKeyboard + +@synthesize hideKeyboardAccessoryBar = _hideKeyboardAccessoryBar; +@synthesize disableScroll = _disableScroll; +//@synthesize styleDark = _styleDark; + +- (void)pluginInitialize { + + NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; + __weak IonicKeyboard* weakSelf = self; + + //set defaults + self.hideKeyboardAccessoryBar = NO; + self.disableScroll = NO; + //self.styleDark = NO; + + _keyboardShowObserver = [nc addObserverForName:UIKeyboardWillShowNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* notification) { + + CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; + keyboardFrame = [self.viewController.view convertRect:keyboardFrame fromView:nil]; + + [weakSelf.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.plugins.Keyboard.isVisible = true; cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight': %@ }); ", [@(keyboardFrame.size.height) stringValue]]]; + + //deprecated + [weakSelf.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight': %@ }); ", [@(keyboardFrame.size.height) stringValue]]]; + }]; + + _keyboardHideObserver = [nc addObserverForName:UIKeyboardWillHideNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* notification) { + [weakSelf.commandDelegate evalJs:@"cordova.plugins.Keyboard.isVisible = false; cordova.fireWindowEvent('native.keyboardhide'); "]; + + //deprecated + [weakSelf.commandDelegate evalJs:@"cordova.fireWindowEvent('native.hidekeyboard'); "]; + }]; +} +- (BOOL)disableScroll { + return _disableScroll; +} + +- (void)setDisableScroll:(BOOL)disableScroll { + if (disableScroll == _disableScroll) { + return; + } + if (disableScroll) { + self.webView.scrollView.scrollEnabled = NO; + self.webView.scrollView.delegate = self; + } + else { + self.webView.scrollView.scrollEnabled = YES; + self.webView.scrollView.delegate = nil; + } + + _disableScroll = disableScroll; +} + + +- (BOOL)hideKeyboardAccessoryBar { + return _hideKeyboardAccessoryBar; +} + +- (void)setHideKeyboardAccessoryBar:(BOOL)hideKeyboardAccessoryBar { + if (hideKeyboardAccessoryBar == _hideKeyboardAccessoryBar) { + return; + } + if (hideKeyboardAccessoryBar) { + self.webView.hackishlyHidesInputAccessoryView = YES; + } + else { + self.webView.hackishlyHidesInputAccessoryView = NO; + } + + _hideKeyboardAccessoryBar = hideKeyboardAccessoryBar; +} + +/* +- (BOOL)styleDark { + return _styleDark; +} + +- (void)setStyleDark:(BOOL)styleDark { + if (styleDark == _styleDark) { + return; + } + if (styleDark) { + self.webView.styleDark = YES; + } + else { + self.webView.styleDark = NO; + } + + _styleDark = styleDark; +} +*/ + + +/* ------------------------------------------------------------- */ + +- (void)scrollViewDidScroll:(UIScrollView *)scrollView { + [scrollView setContentOffset: CGPointZero]; +} + +/* ------------------------------------------------------------- */ + +- (void)dealloc { + NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; + + [nc removeObserver:self name:UIKeyboardWillShowNotification object:nil]; + [nc removeObserver:self name:UIKeyboardWillHideNotification object:nil]; +} + +/* ------------------------------------------------------------- */ + +- (void) disableScroll:(CDVInvokedUrlCommand*)command { + if (!command.arguments || ![command.arguments count]){ + return; + } + id value = [command.arguments objectAtIndex:0]; + + self.disableScroll = [value boolValue]; +} + +- (void) hideKeyboardAccessoryBar:(CDVInvokedUrlCommand*)command { + if (!command.arguments || ![command.arguments count]){ + return; + } + id value = [command.arguments objectAtIndex:0]; + + self.hideKeyboardAccessoryBar = [value boolValue]; +} + +- (void) close:(CDVInvokedUrlCommand*)command { + [self.webView endEditing:YES]; +} + +- (void) show:(CDVInvokedUrlCommand*)command { + NSLog(@"Showing keyboard not supported in iOS due to platform limitations."); +} + +/* +- (void) styleDark:(CDVInvokedUrlCommand*)command { + if (!command.arguments || ![command.arguments count]){ + return; + } + id value = [command.arguments objectAtIndex:0]; + + self.styleDark = [value boolValue]; +} +*/ + +@end + diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/ios/UIWebViewExtension.h b/StoneIsland/plugins/com.ionic.keyboard/src/ios/UIWebViewExtension.h new file mode 100644 index 00000000..1d6c293d --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/ios/UIWebViewExtension.h @@ -0,0 +1,4 @@ +@interface UIWebView (HackishAccessoryHiding) +@property (nonatomic, assign) BOOL hackishlyHidesInputAccessoryView; +//@property (nonatomic, assign) BOOL styleDark; +@end diff --git a/StoneIsland/plugins/com.ionic.keyboard/src/ios/UIWebViewExtension.m b/StoneIsland/plugins/com.ionic.keyboard/src/ios/UIWebViewExtension.m new file mode 100644 index 00000000..25403e6f --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/src/ios/UIWebViewExtension.m @@ -0,0 +1,109 @@ +#import <objc/runtime.h> +#import <UIKit/UIKit.h> +#import "UIWebViewExtension.h" + +//Credit: https://gist.github.com/bjhomer/2048571 +//Also: http://stackoverflow.com/a/23398487/1091751 +@implementation UIWebView (HackishAccessoryHiding) + +static const char * const hackishFixClassName = "UIWebBrowserViewMinusAccessoryView"; +static Class hackishFixClass = Nil; + +- (UIView *)hackishlyFoundBrowserView { + UIScrollView *scrollView = self.scrollView; + + UIView *browserView = nil; + for (UIView *subview in scrollView.subviews) { + if ([NSStringFromClass([subview class]) hasPrefix:@"UIWebBrowserView"]) { + browserView = subview; + break; + } + } + return browserView; +} + +- (id)methodReturningNil { + return nil; +} + +- (void)ensureHackishSubclassExistsOfBrowserViewClass:(Class)browserViewClass { + if (!hackishFixClass) { + Class newClass = objc_allocateClassPair(browserViewClass, hackishFixClassName, 0); + IMP nilImp = [self methodForSelector:@selector(methodReturningNil)]; + class_addMethod(newClass, @selector(inputAccessoryView), nilImp, "@@:"); + objc_registerClassPair(newClass); + + hackishFixClass = newClass; + } +} + +- (BOOL) hackishlyHidesInputAccessoryView { + UIView *browserView = [self hackishlyFoundBrowserView]; + return [browserView class] == hackishFixClass; +} + +- (void) setHackishlyHidesInputAccessoryView:(BOOL)value { + UIView *browserView = [self hackishlyFoundBrowserView]; + if (browserView == nil) { + return; + } + [self ensureHackishSubclassExistsOfBrowserViewClass:[browserView class]]; + + if (value) { + object_setClass(browserView, hackishFixClass); + } + else { + Class normalClass = objc_getClass("UIWebBrowserView"); + object_setClass(browserView, normalClass); + } + [browserView reloadInputViews]; +} +/* ---------------------------------------------------------------- */ + +/* +- (UIKeyboardAppearance) darkKeyboardAppearanceTemplateMethod { + return UIKeyboardAppearanceDark; +} + +- (UIKeyboardAppearance) lightKeyboardAppearanceTemplateMethod { + return UIKeyboardAppearanceLight; +} + +- (BOOL) styleDark { + UIView *browserView = [self hackishlyFoundBrowserView]; + if (browserView == nil) { + return false; + } + + Method m = class_getInstanceMethod( [self class], @selector( darkKeyboardAppearanceTemplateMethod ) ); + IMP imp = method_getImplementation( m ); + + Method m2 = class_getInstanceMethod( [browserView class], @selector(keyboardAppearance) ); + IMP imp2 = method_getImplementation( m2 ); + + return imp == imp2; +} + +- (void) setStyleDark:(BOOL)styleDark { + UIView *browserView = [self hackishlyFoundBrowserView]; + if (browserView == nil) { + return; + } + + if ( styleDark ) { + Method m = class_getInstanceMethod( [self class], @selector( darkKeyboardAppearanceTemplateMethod ) ); + IMP imp = method_getImplementation( m ); + const char* typeEncoding = method_getTypeEncoding( m ); + class_replaceMethod( [browserView class], @selector(keyboardAppearance), imp, typeEncoding ); + } + else { + Method m = class_getInstanceMethod( [self class], @selector( lightKeyboardAppearanceTemplateMethod ) ); + IMP imp = method_getImplementation( m ); + const char* typeEncoding = method_getTypeEncoding( m ); + class_replaceMethod( [browserView class], @selector(keyboardAppearance), imp, typeEncoding ); + } +} +*/ + +@end + diff --git a/StoneIsland/plugins/com.ionic.keyboard/www/keyboard.js b/StoneIsland/plugins/com.ionic.keyboard/www/keyboard.js new file mode 100644 index 00000000..21b3bf63 --- /dev/null +++ b/StoneIsland/plugins/com.ionic.keyboard/www/keyboard.js @@ -0,0 +1,37 @@ + +var argscheck = require('cordova/argscheck'), + utils = require('cordova/utils'), + exec = require('cordova/exec'); + + +var Keyboard = function() { +}; + +Keyboard.hideKeyboardAccessoryBar = function(hide) { + exec(null, null, "Keyboard", "hideKeyboardAccessoryBar", [hide]); +}; + +Keyboard.close = function() { + exec(null, null, "Keyboard", "close", []); +}; + +Keyboard.show = function() { + exec(null, null, "Keyboard", "show", []); +}; + +Keyboard.disableScroll = function(disable) { + exec(null, null, "Keyboard", "disableScroll", [disable]); +}; + +/* +Keyboard.styleDark = function(dark) { + exec(null, null, "Keyboard", "styleDark", [dark]); +}; +*/ + +Keyboard.isVisible = false; + +module.exports = Keyboard; + + + diff --git a/StoneIsland/plugins/cordova-plugin-console/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-console/CONTRIBUTING.md new file mode 100644 index 00000000..f7dbcaba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-console/LICENSE b/StoneIsland/plugins/cordova-plugin-console/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/NOTICE b/StoneIsland/plugins/cordova-plugin-console/NOTICE new file mode 100644 index 00000000..8ec56a52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/StoneIsland/plugins/cordova-plugin-console/README.md b/StoneIsland/plugins/cordova-plugin-console/README.md new file mode 100644 index 00000000..73e89084 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/README.md @@ -0,0 +1,48 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +This plugin is meant to ensure that console.log() is as useful as it can be. +It adds additional function for iOS, Ubuntu, Windows Phone 8, and Windows. If +you are happy with how console.log() works for you, then you probably +don't need this plugin. + +This plugin defines a global `console` object. + +Although the object is in the global scope, features provided by this plugin +are not available until after the `deviceready` event. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + +## Installation + + cordova plugin add cordova-plugin-console + +### Android Quirks + +On some platforms other than Android, console.log() will act on multiple +arguments, such as console.log("1", "2", "3"). However, Android will act only +on the first argument. Subsequent arguments to console.log() will be ignored. +This plugin is not the cause of that, it is a limitation of Android itself. diff --git a/StoneIsland/plugins/cordova-plugin-console/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-console/RELEASENOTES.md new file mode 100644 index 00000000..5b1fdd1d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/RELEASENOTES.md @@ -0,0 +1,84 @@ +<!-- +# +# 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. +# +--> +# Release Notes + +### 0.2.3 (Sept 25, 2013) +* CB-4889 bumping&resetting version +* CB-4889 renaming org.apache.cordova.core.console to org.apache.cordova.console +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4752] Incremented plugin version on dev branch. + + ### 0.2.4 (Oct 28, 2013) +* CB-5154 log formatting incorrectly to native +* CB-5128: added repo + issue tag to plugin.xml for console plugin +* [CB-4915] Incremented plugin version on dev branch. + +### 0.2.5 (Dec 4, 2013) +* add ubuntu platform + +### 0.2.6 (Jan 02, 2014) +* CB-5658 Add doc/index.md for Console plugin + +### 0.2.7 (Feb 05, 2014) +* Native console needs to be called DebugConsole to avoid ambiguous reference. This commit requires the 3.4.0 version of the native class factory +* CB-4718 fixed Console plugin not working on wp + +### 0.2.8 (Apr 17, 2014) +* CB-6460: Update license headers +* Add NOTICE file + +### 0.2.9 (Jun 05, 2014) +* CB-6848 Add Android quirk, list applicable platforms +* CB-6796 Add license +* CB-6491 add CONTRIBUTING.md + +### 0.2.10 (Aug 06, 2014) +* CB-6127 Updated translations for docs + +### 0.2.11 (Sep 17, 2014) +* CB-7249 cordova-plugin-console documentation translation + +### 0.2.12 (Dec 02, 2014) +* CB-7977 Mention `deviceready` in plugin docs +* CB-7700 cordova-plugin-console documentation translation: cordova-plugin-console + +### 0.2.13 (Feb 04, 2015) +* CB-8351 ios: Use argumentForIndex rather than NSArray extension + +### 1.0.0 (Apr 15, 2015) +* CB-8746 gave plugin major version bump +* CB-8683 changed plugin-id to pacakge-name +* CB-8653 updated translated docs to use new id +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* docs: renamed Windows8 to Windows +* CB-8653 Updated Readme +* CB-8560 Integrate TravisCI +* CB-8438 cordova-plugin-console documentation translation: cordova-plugin-console +* CB-8538 Added package.json file +* CB-8362 Add Windows platform section to Console plugin + +### 1.0.1 (Jun 17, 2015) +* move logger.js and console-via-logger.js to common modules, instead of the numerous repeats that were there. +* clean up tests, info is below log level so it does not exist by default. +* add a couple tests +* CB-9191 Add basic test +* CB-9128 cordova-plugin-console documentation translation: cordova-plugin-console +* attempt to fix npm markdown issue diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/de/README.md new file mode 100644 index 00000000..933c1b7a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/de/README.md @@ -0,0 +1,43 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +Dieses Plugin stellt sicher, dass der Befehl console.log() so hilfreich ist, wie er sein kann. Es fügt zusätzliche Funktion für iOS, Ubuntu, Windows Phone 8 und Windows. Teilweise kann es vorkommen, dass der Befehl console.log() nicht korrekt erkannt wird, und es zu Fehlern bzw. zu nicht angezeigten Logs in der Console kommt. Wenn Sie mit der derzeitigen Funktionsweise zufrieden sind, kann es sein, dass Sie dieses Plugin nicht benötigen. + +Dieses Plugin wird ein global-`console`-Objekt definiert. + +Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## Installation + + cordova plugin add cordova-plugin-console + + +### Android Eigenarten + +Auf einigen Plattformen als Android fungieren console.log() auf mehrere Argumente wie console.log ("1", "2", "3"). Android wird jedoch nur auf das erste Argument fungieren. Nachfolgende Argumente zu console.log() werden ignoriert. Dieses Plugin ist nicht die Verantwortung dafür, es ist eine Einschränkung von Android selbst.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/de/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/de/index.md new file mode 100644 index 00000000..95517827 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/de/index.md @@ -0,0 +1,41 @@ +<!--- + 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-plugin-console + +Dieses Plugin stellt sicher, dass der Befehl console.log() so hilfreich ist, wie er sein kann. Es fügt zusätzliche Funktion für iOS, Ubuntu, Windows Phone 8 und Windows 8 hinzu. Teilweise kann es vorkommen, dass der Befehl console.log() nicht korrekt erkannt wird, und es zu Fehlern bzw. zu nicht angezeigten Logs in der Console kommt. Wenn Sie mit der derzeitigen Funktionsweise zufrieden sind, kann es sein, dass Sie dieses Plugin nicht benötigen. + +Dieses Plugin wird ein global-`console`-Objekt definiert. + +Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## Installation + + cordova plugin add cordova-plugin-console + + +### Android Eigenarten + +Auf einigen Plattformen als Android fungieren console.log() auf mehrere Argumente wie console.log ("1", "2", "3"). Android wird jedoch nur auf das erste Argument fungieren. Nachfolgende Argumente zu console.log() werden ignoriert. Dieses Plugin ist nicht die Verantwortung dafür, es ist eine Einschränkung von Android selbst. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/es/README.md new file mode 100644 index 00000000..b089d639 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/es/README.md @@ -0,0 +1,41 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +Este plugin es para asegurarse de que console.log() es tan útil como puede ser. Agrega la función adicional para iOS, Ubuntu, Windows Phone 8 y Windows. Si estás contento con cómo funciona console.log() para ti, entonces probablemente no necesitas este plugin. + +Este plugin define un global `console` objeto. + +Aunque el objeto está en el ámbito global, caracterÃsticas proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log ("console.log funciona bien");} + + +## Instalación + + cordova plugin add cordova-plugin-console + + +### Rarezas Android + +En algunas plataformas que no sean Android, console.log() actuará en varios argumentos, como console.log ("1", "2", "3"). Sin embargo, Android actuará sólo en el primer argumento. Se omitirá posteriores argumentos para console.log(). Este plugin no es la causa de eso, es una limitación propia de Android.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/es/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/es/index.md new file mode 100644 index 00000000..e6b8e684 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/es/index.md @@ -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. +--> + +# cordova-plugin-console + +Este plugin es para asegurarse de que console.log() es tan útil como puede ser. Añade función adicional para iOS, Windows Phone 8, Ubuntu y Windows 8. Si estás contento con cómo funciona console.log() para ti, entonces probablemente no necesitas este plugin. + +Este plugin define un global `console` objeto. + +Aunque el objeto está en el ámbito global, caracterÃsticas proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log ("console.log funciona bien");} + + +## Instalación + + Cordova plugin agregar cordova-plugin-console + + +### Rarezas Android + +En algunas plataformas que no sean Android, console.log() actuará en varios argumentos, como console.log ("1", "2", "3"). Sin embargo, Android actuará sólo en el primer argumento. Se omitirá posteriores argumentos para console.log(). Este plugin no es la causa de eso, es una limitación propia de Android. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/fr/README.md new file mode 100644 index 00000000..74207ac4 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/fr/README.md @@ -0,0 +1,41 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +Ce plugin est destiné à faire en sorte que console.log() est aussi utile que possible. Il ajoute une fonction supplémentaire pour iOS, Ubuntu, Windows Phone 8 et Windows. Si vous êtes satisfait du fonctionnement de console.log() pour vous, alors vous avez probablement pas besoin ce plugin. + +Ce plugin définit un global `console` objet. + +Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log ("console.log fonctionne bien");} + + +## Installation + + cordova plugin add cordova-plugin-console + + +### Quirks Android + +Sur certaines plateformes autres que Android, console.log() va agir sur plusieurs arguments, tels que console.log ("1", "2", "3"). Toutefois, Android doit agir uniquement sur le premier argument. Les arguments suivants à console.log() seront ignorées. Ce plugin n'est pas la cause de cela, il s'agit d'une limitation d'Android lui-même.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/fr/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/fr/index.md new file mode 100644 index 00000000..d0dbba55 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/fr/index.md @@ -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. +--> + +# cordova-plugin-console + +Ce plugin est destiné à faire en sorte que console.log() est aussi utile que possible. Il ajoute une fonction supplémentaire pour iOS, Ubuntu, Windows Phone 8 et Windows 8. Si vous êtes satisfait du fonctionnement de console.log() pour vous, alors vous avez probablement pas besoin ce plugin. + +Ce plugin définit un global `console` objet. + +Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log ("console.log fonctionne bien");} + + +## Installation + + Cordova plugin ajouter cordova-plugin-console + + +### Quirks Android + +Sur certaines plateformes autres que Android, console.log() va agir sur plusieurs arguments, tels que console.log ("1", "2", "3"). Toutefois, Android doit agir uniquement sur le premier argument. Les arguments suivants à console.log() seront ignorées. Ce plugin n'est pas la cause de cela, il s'agit d'une limitation d'Android lui-même. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/it/README.md new file mode 100644 index 00000000..5394d551 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/it/README.md @@ -0,0 +1,43 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +Questo plugin è intesa a garantire che console.log() è tanto utile quanto può essere. Aggiunge una funzione aggiuntiva per iOS, Ubuntu, Windows Phone 8 e Windows. Se sei soddisfatto di come console.log() funziona per voi, quindi probabilmente non è necessario questo plugin. + +Questo plugin definisce un oggetto globale `console`. + +Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## Installazione + + cordova plugin add cordova-plugin-console + + +### Stranezze Android + +Su alcune piattaforme diverse da Android, console.log() agirà su più argomenti, come ad esempio console ("1", "2", "3"). Tuttavia, Android agirà solo sul primo argomento. Argomenti successivi a console.log() verranno ignorati. Questo plugin non è la causa di ciò, è una limitazione di Android stesso.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/it/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/it/index.md new file mode 100644 index 00000000..f0625b39 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/it/index.md @@ -0,0 +1,41 @@ +<!--- + 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-plugin-console + +Questo plugin è intesa a garantire che console.log() è tanto utile quanto può essere. Aggiunge una funzione aggiuntiva per iOS, Ubuntu, Windows 8 e Windows Phone 8. Se sei soddisfatto di come console.log() funziona per voi, quindi probabilmente non è necessario questo plugin. + +Questo plugin definisce un oggetto globale `console`. + +Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## Installazione + + cordova plugin add cordova-plugin-console + + +### Stranezze Android + +Su alcune piattaforme diverse da Android, console.log() agirà su più argomenti, come ad esempio console ("1", "2", "3"). Tuttavia, Android agirà solo sul primo argomento. Argomenti successivi a console.log() verranno ignorati. Questo plugin non è la causa di ciò, è una limitazione di Android stesso. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/ja/README.md new file mode 100644 index 00000000..059c373c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/ja/README.md @@ -0,0 +1,43 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +ã“ã®ãƒ—ラグインã¯ã€ãã® console.log() ãŒã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ä¾¿åˆ©ãªã“ã¨ã‚’確èªã™ã‚‹ã‚‚ã®ã§ã™ã€‚ ãれ㯠iOSã€Ubuntuã€Windows Phone 8 ã¯ã€Windows ã«è¿½åŠ ã®é–¢æ•°ã‚’è¿½åŠ ã—ã¾ã™ã€‚ å ´åˆã¯ã‚ãªãŸã®ãŸã‚ã® console.log() ã®ä½œå“ã«æº€è¶³ã—ã¦ã„ã‚‹ã—ã€ãŠãらãå¿…è¦ã¯ã‚りã¾ã›ã‚“ã“ã®ãƒ—ラグイン。 + +ã“ã®ãƒ—ラグインã§ã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« ・ `console` オブジェクトを定義ã—ã¾ã™ã€‚ + +オブジェクトã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã§ã™ãŒã€ã“ã®ãƒ—ラグインã«ã‚ˆã£ã¦æä¾›ã•れる機能ã¯ã€`deviceready` イベントã®å¾Œã¾ã§ä½¿ç”¨ã§ãã¾ã›ã‚“。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## インストール + + cordova plugin add cordova-plugin-console + + +### Android ã®ç™– + +アンドãƒã‚¤ãƒ‰ä»¥å¤–ã®ã„ãã¤ã‹ã®ãƒ—ラットフォーム㧠console.log() 㯠console.log (「1ã€ã€ã€Œ2ã€ã€ã€Œ3ã€) ãªã©ã€è¤‡æ•°ã®å¼•æ•°ã«å‹•作ã—ã¾ã™ã€‚ ã—ã‹ã—ã€ã‚¢ãƒ³ãƒ‰ãƒã‚¤ãƒ‰ã¯ã€æœ€åˆã®å¼•æ•°ã§ã®ã¿å‹•作ã—ã¾ã™ã€‚ console.log() ã«å¾Œç¶šã®å¼•æ•°ã¯ç„¡è¦–ã•れã¾ã™ã€‚ ã“ã®ãƒ—ラグインãŒåŽŸå› ã§ã¯ãªã„ã€ãれ㯠Android ã®è‡ªä½“ã®åˆ¶é™ã§ã™ã€‚
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/ja/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/ja/index.md new file mode 100644 index 00000000..413593ce --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/ja/index.md @@ -0,0 +1,41 @@ +<!--- + 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-plugin-console + +ã“ã®ãƒ—ラグインã¯ã€ãã® console.log() ãŒã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ä¾¿åˆ©ãªã“ã¨ã‚’確èªã™ã‚‹ã‚‚ã®ã§ã™ã€‚ ãれã¯ã€iOSã€Ubuntuã€Windows Phone 8 ãŠã‚ˆã³ Windows 8 ã®è¿½åŠ é–¢æ•°ã‚’è¿½åŠ ã—ã¾ã™ã€‚ å ´åˆã¯ã‚ãªãŸã®ãŸã‚ã® console.log() ã®ä½œå“ã«æº€è¶³ã—ã¦ã„ã‚‹ã—ã€ãŠãらãå¿…è¦ã¯ã‚りã¾ã›ã‚“ã“ã®ãƒ—ラグイン。 + +ã“ã®ãƒ—ラグインã§ã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« ・ `console` オブジェクトを定義ã—ã¾ã™ã€‚ + +オブジェクトã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã§ã™ãŒã€ã“ã®ãƒ—ラグインã«ã‚ˆã£ã¦æä¾›ã•れる機能ã¯ã€`deviceready` イベントã®å¾Œã¾ã§ä½¿ç”¨ã§ãã¾ã›ã‚“。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## インストール + + cordova plugin add cordova-plugin-console + + +### Android ã®ç™– + +アンドãƒã‚¤ãƒ‰ä»¥å¤–ã®ã„ãã¤ã‹ã®ãƒ—ラットフォーム㧠console.log() 㯠console.log (「1ã€ã€ã€Œ2ã€ã€ã€Œ3ã€) ãªã©ã€è¤‡æ•°ã®å¼•æ•°ã«å‹•作ã—ã¾ã™ã€‚ ã—ã‹ã—ã€ã‚¢ãƒ³ãƒ‰ãƒã‚¤ãƒ‰ã¯ã€æœ€åˆã®å¼•æ•°ã§ã®ã¿å‹•作ã—ã¾ã™ã€‚ console.log() ã«å¾Œç¶šã®å¼•æ•°ã¯ç„¡è¦–ã•れã¾ã™ã€‚ ã“ã®ãƒ—ラグインãŒåŽŸå› ã§ã¯ãªã„ã€ãれ㯠Android ã®è‡ªä½“ã®åˆ¶é™ã§ã™ã€‚ diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/ko/README.md new file mode 100644 index 00000000..d03ee5aa --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/ko/README.md @@ -0,0 +1,43 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +ì´ í”ŒëŸ¬ê·¸ì¸ì„ console.log()로 수 ìœ ìš© ë˜ë„ë¡ ì˜ë¯¸ìž…니다. ê·¸ê²ƒì€ iOS, 우분투, Windows Phone 8, ë° ì°½ì— ëŒ€ 한 추가 ê¸°ëŠ¥ì„ ì¶”ê°€í•©ë‹ˆë‹¤. Console.log() ë‹¹ì‹ ì„ ìœ„í•´ ìž‘ë™ í•˜ëŠ” 어떻게 행복 한 경우ì—, 그때 ë‹¹ì‹ ì€ ì•„ë§ˆ í•„ìš” 하지 ì•ŠìŠµë‹ˆë‹¤ì´ í”ŒëŸ¬ê·¸ì¸. + +ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `console` 개체를 ì •ì˜í•©ë‹ˆë‹¤. + +개체가 ì „ì— ë²”ìœ„ì— ìžˆì§€ë§Œ,ì´ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ ì œê³µ ë˜ëŠ” 기능 하지 ì‚¬ìš©í• ìˆ˜ 있습니다까지 `deviceready` ì´ë²¤íЏ 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## 설치 + + cordova plugin add cordova-plugin-console + + +### 안 드 로ì´ë“œ 단ì + +안 드 로ì´ë“œ ì´ì™¸ì˜ ì¼ë¶€ 플랫í¼ì—서 console.log() console.log ("1", "2", "3")와 ê°™ì´ ì—¬ëŸ¬ ì¸ìˆ˜ì— ìž‘ë™í• 것 ì´ë‹¤. 그러나, 안 드 로ì´ë“œëŠ” 첫 번째 ì¸ìˆ˜ì—ë§Œ ìž‘ë™í• 것 ì´ë‹¤. Console.log() í›„ì† ì¸ìˆ˜ëŠ” 무시 ë©ë‹ˆë‹¤. ì´ í”ŒëŸ¬ê·¸ì¸ì˜ ì›ì¸ì´ ë˜ì§€ 않습니다, ê·¸ë¦¬ê³ ê·¸ê²ƒì€ ì•ˆ 드 로ì´ë“œ ìžì²´ì˜ 한계입니다.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/ko/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/ko/index.md new file mode 100644 index 00000000..ca631e44 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/ko/index.md @@ -0,0 +1,41 @@ +<!--- + 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-plugin-console + +ì´ í”ŒëŸ¬ê·¸ì¸ì„ console.log()로 수 ìœ ìš© ë˜ë„ë¡ ì˜ë¯¸ìž…니다. IOS, 우분투, Windows Phone 8 ë° ìœˆë„ìš° 8ì— ëŒ€ 한 추가 ê¸°ëŠ¥ì„ ì¶”ê°€ 하 ê³ í•©ë‹ˆë‹¤. Console.log() ë‹¹ì‹ ì„ ìœ„í•´ ìž‘ë™ í•˜ëŠ” 어떻게 행복 한 경우ì—, 그때 ë‹¹ì‹ ì€ ì•„ë§ˆ í•„ìš” 하지 ì•ŠìŠµë‹ˆë‹¤ì´ í”ŒëŸ¬ê·¸ì¸. + +ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `console` 개체를 ì •ì˜í•©ë‹ˆë‹¤. + +개체가 ì „ì— ë²”ìœ„ì— ìžˆì§€ë§Œ,ì´ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ ì œê³µ ë˜ëŠ” 기능 하지 ì‚¬ìš©í• ìˆ˜ 있습니다까지 `deviceready` ì´ë²¤íЏ 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## 설치 + + cordova plugin add cordova-plugin-console + + +### 안 드 로ì´ë“œ 단ì + +안 드 로ì´ë“œ ì´ì™¸ì˜ ì¼ë¶€ 플랫í¼ì—서 console.log() console.log ("1", "2", "3")와 ê°™ì´ ì—¬ëŸ¬ ì¸ìˆ˜ì— ìž‘ë™í• 것 ì´ë‹¤. 그러나, 안 드 로ì´ë“œëŠ” 첫 번째 ì¸ìˆ˜ì—ë§Œ ìž‘ë™í• 것 ì´ë‹¤. Console.log() í›„ì† ì¸ìˆ˜ëŠ” 무시 ë©ë‹ˆë‹¤. ì´ í”ŒëŸ¬ê·¸ì¸ì˜ ì›ì¸ì´ ë˜ì§€ 않습니다, ê·¸ë¦¬ê³ ê·¸ê²ƒì€ ì•ˆ 드 로ì´ë“œ ìžì²´ì˜ 한계입니다. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/pl/README.md new file mode 100644 index 00000000..78ab9d2c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/pl/README.md @@ -0,0 +1,43 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +Ten plugin jest przeznaczona do zapewnienia, że console.log() jest tak przydatne, jak to może być. To dodaje dodatkowÄ… funkcjÄ™ dla iOS, Ubuntu, Windows Phone 8 i Windows. JeÅ›li jesteÅ› zadowolony z jak console.log() pracuje dla Ciebie, wtedy prawdopodobnie nie potrzebujÄ… tej wtyczki. + +Ten plugin definiuje obiekt globalny `console`. + +Mimo, że obiekt jest w globalnym zasiÄ™gu, funkcji oferowanych przez ten plugin nie sÄ… dostÄ™pne dopiero po turnieju `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## Instalacja + + cordova plugin add cordova-plugin-console + + +### Dziwactwa Androida + +Na niektórych platformach innych niż Android console.log() bÄ™dzie dziaÅ‚ać na wielu argumentów, takich jak console.log ("1", "2", "3"). Jednak Android bÄ™dzie dziaÅ‚ać tylko na pierwszy argument. Kolejne argumenty do console.log() bÄ™dÄ… ignorowane. Ten plugin nie jest przyczynÄ…, że, jest to ograniczenie Androida, sam.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/pl/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/pl/index.md new file mode 100644 index 00000000..922b577c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/pl/index.md @@ -0,0 +1,41 @@ +<!--- + 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-plugin-console + +Ten plugin jest przeznaczona do zapewnienia, że console.log() jest tak przydatne, jak to może być. To dodaje dodatkowÄ… funkcjÄ™ dla iOS, Ubuntu, Windows Phone 8 i Windows 8. JeÅ›li jesteÅ› zadowolony z jak console.log() pracuje dla Ciebie, wtedy prawdopodobnie nie potrzebujÄ… tej wtyczki. + +Ten plugin definiuje obiekt globalny `console`. + +Mimo, że obiekt jest w globalnym zasiÄ™gu, funkcji oferowanych przez ten plugin nie sÄ… dostÄ™pne dopiero po turnieju `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## Instalacja + + cordova plugin add cordova-plugin-console + + +### Dziwactwa Androida + +Na niektórych platformach innych niż Android console.log() bÄ™dzie dziaÅ‚ać na wielu argumentów, takich jak console.log ("1", "2", "3"). Jednak Android bÄ™dzie dziaÅ‚ać tylko na pierwszy argument. Kolejne argumenty do console.log() bÄ™dÄ… ignorowane. Ten plugin nie jest przyczynÄ…, że, jest to ograniczenie Androida, sam. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/ru/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/ru/index.md new file mode 100644 index 00000000..3cfe15dc --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/ru/index.md @@ -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. +--> + +# cordova-plugin-console + +Ðтот плагин предназначен Ð´Ð»Ñ Ð¾Ð±ÐµÑÐ¿ÐµÑ‡ÐµÐ½Ð¸Ñ ÐºÐ°Ðº полезным, поÑкольку Ñто может быть что console.log(). Он добавлÑет дополнительные функции Ð´Ð»Ñ iOS, Ubuntu, Windows Phone 8 и Windows 8. ЕÑли вы не довольны как console.log() работает Ð´Ð»Ñ Ð²Ð°Ñ, то вы вероÑтно не нужен Ñтот плагин. + +## УÑтановка + + cordova plugin add cordova-plugin-console + + +### ОÑобенноÑти Android + +Ðа некоторых платформах, отличных от Android console.log() будет дейÑтвовать на неÑкольких аргументов, например console.log («1», «2», «3»). Тем не менее Android будет дейÑтвовать только на первого аргумента. ПоÑледующие аргументы Ð´Ð»Ñ console.log() будет игнорироватьÑÑ. Ðтот плагин не ÑвлÑетÑÑ Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½Ð¾Ð¹ Ñтого, Ñто ограничение Android Ñам. diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-console/doc/zh/README.md new file mode 100644 index 00000000..ce27c3e1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/zh/README.md @@ -0,0 +1,43 @@ +<!--- +# license: 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-plugin-console + +[](https://travis-ci.org/apache/cordova-plugin-console) + +é€™å€‹å¤–æŽ›ç¨‹å¼æ˜¯ç‚ºäº†ç¢ºä¿è©² console.log() 是一樣有用,它å¯ä»¥æ˜¯ã€‚ å®ƒå°‡æ·»åŠ é™„åŠ åŠŸèƒ½çš„ iOS,Ubuntu,Windows Phone 8 和視窗。 å¦‚æžœä½ æ˜¯å¿«æ¨‚èˆ‡ console.log() æ˜¯å¦‚ä½•ç‚ºä½ å·¥ä½œï¼Œé‚£éº¼å¯èƒ½ä¸éœ€è¦é€™å€‹å¤–掛程å¼ã€‚ + +這個外掛程å¼å®šç¾©äº†ä¸€å€‹å…¨åŸŸ `console` 物件。 + +儘管物件是在全çƒç¯„åœå…§ï¼Œæä¾›é€™å€‹å¤–掛程å¼çš„功能ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-console + + +### Android 的怪癖 + +在一些平臺上除了 Android,console.log() äº¦æœƒæ ¹æ“šå¤šå€‹åƒæ•¸ï¼Œå¦‚ console.log ("1"ã€"2"ã€"3")。 然而,安å“系統åªäº¦æœƒæ ¹æ“šç¬¬ä¸€å€‹åƒæ•¸ã€‚ å° console.log() çš„å¾ŒçºŒåƒæ•¸å°‡è¢«å¿½ç•¥ã€‚ 這個外掛程å¼ä¸æ˜¯çš„åŽŸå› ï¼Œå®ƒæ˜¯ä¸€å€‹ android 作æ¥ç³»çµ±æœ¬èº«çš„é™åˆ¶ã€‚
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-console/doc/zh/index.md b/StoneIsland/plugins/cordova-plugin-console/doc/zh/index.md new file mode 100644 index 00000000..e18a141b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/doc/zh/index.md @@ -0,0 +1,41 @@ +<!--- + 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-plugin-console + +é€™å€‹å¤–æŽ›ç¨‹å¼æ˜¯ç‚ºäº†ç¢ºä¿è©² console.log() 是一樣有用,它å¯ä»¥æ˜¯ã€‚ å®ƒå°‡æ·»åŠ é™„åŠ åŠŸèƒ½çš„ iOS〠Ubuntu,Windows Phone 8 å’Œ Windows 8。 å¦‚æžœä½ æ˜¯å¿«æ¨‚èˆ‡ console.log() æ˜¯å¦‚ä½•ç‚ºä½ å·¥ä½œï¼Œé‚£éº¼å¯èƒ½ä¸éœ€è¦é€™å€‹å¤–掛程å¼ã€‚ + +這個外掛程å¼å®šç¾©äº†ä¸€å€‹å…¨åŸŸ `console` 物件。 + +儘管物件是在全çƒç¯„åœå…§ï¼Œæä¾›é€™å€‹å¤–掛程å¼çš„功能ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("console.log works well"); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-console + + +### Android 的怪癖 + +在一些平臺上除了 Android,console.log() äº¦æœƒæ ¹æ“šå¤šå€‹åƒæ•¸ï¼Œå¦‚ console.log ("1"ã€"2"ã€"3")。 然而,安å“系統åªäº¦æœƒæ ¹æ“šç¬¬ä¸€å€‹åƒæ•¸ã€‚ å° console.log() çš„å¾ŒçºŒåƒæ•¸å°‡è¢«å¿½ç•¥ã€‚ 這個外掛程å¼ä¸æ˜¯çš„åŽŸå› ï¼Œå®ƒæ˜¯ä¸€å€‹ android 作æ¥ç³»çµ±æœ¬èº«çš„é™åˆ¶ã€‚ diff --git a/StoneIsland/plugins/cordova-plugin-console/package.json b/StoneIsland/plugins/cordova-plugin-console/package.json new file mode 100644 index 00000000..9f667f00 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/package.json @@ -0,0 +1,33 @@ +{ + "name": "cordova-plugin-console", + "version": "1.0.1", + "description": "Cordova Console Plugin", + "cordova": { + "id": "cordova-plugin-console", + "platforms": [ + "ios", + "ubuntu", + "wp7", + "wp8", + "windows8", + "windows" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-console" + }, + "keywords": [ + "cordova", + "console", + "ecosystem:cordova", + "cordova-ios", + "cordova-ubuntu", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows" + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-console/plugin.xml b/StoneIsland/plugins/cordova-plugin-console/plugin.xml new file mode 100644 index 00000000..f902cc74 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/plugin.xml @@ -0,0 +1,92 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="cordova-plugin-console" + version="1.0.1"> + + <name>Console</name> + <description>Cordova Console Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,console</keywords> + <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git</repo> + <issue>https://issues.apache.org/jira/browse/CB/component/12320644</issue> + + <js-module src="www/logger.js" name="logger"> + <clobbers target="cordova.logger" /> + </js-module> + + <js-module src="www/console-via-logger.js" name="console"> + <clobbers target="console" /> + </js-module> + + <!-- ios --> + <platform name="ios"> + + <config-file target="config.xml" parent="/*"> + <feature name="Console"> + <param name="ios-package" value="CDVLogger"/> + </feature> + </config-file> + + <header-file src="src/ios/CDVLogger.h" /> + <source-file src="src/ios/CDVLogger.m" /> + + </platform> + + <!-- ubuntu --> + <platform name="ubuntu"> + + <header-file src="src/ubuntu/console.h" /> + <source-file src="src/ubuntu/console.cpp" /> + + </platform> + + <!-- wp7 --> + <platform name="wp7"> + <config-file target="config.xml" parent="/*"> + <feature name="Console"> + <param name="wp-package" value="DebugConsole"/> + </feature> + </config-file> + + <source-file src="src/wp/DebugConsole.cs" /> + </platform> + + <!-- wp8 --> + <platform name="wp8"> + <config-file target="config.xml" parent="/*"> + <feature name="Console"> + <param name="wp-package" value="DebugConsole"/> + </feature> + </config-file> + + <source-file src="src/wp/DebugConsole.cs" /> + </platform> + + <!-- windows8 --> + <platform name="windows8"> + </platform> + + <!-- Windows universal platform --> + <platform name="windows"> + </platform> + +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-console/src/ios/CDVLogger.h b/StoneIsland/plugins/cordova-plugin-console/src/ios/CDVLogger.h new file mode 100644 index 00000000..7cfb3063 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/src/ios/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; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-console/src/ios/CDVLogger.m b/StoneIsland/plugins/cordova-plugin-console/src/ios/CDVLogger.m new file mode 100644 index 00000000..ccfa3a51 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/src/ios/CDVLogger.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 "CDVLogger.h" +#import <Cordova/CDV.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); + } +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-console/src/ubuntu/console.cpp b/StoneIsland/plugins/cordova-plugin-console/src/ubuntu/console.cpp new file mode 100644 index 00000000..9de09f43 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/src/ubuntu/console.cpp @@ -0,0 +1,29 @@ +/* + * Licensed 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 "console.h" + +#include <iostream> + +Console::Console(Cordova *cordova) : CPlugin(cordova) { +} + +void Console::logLevel(int scId, int ecId, QString level, QString message) { + Q_UNUSED(scId) + Q_UNUSED(ecId) + + if (level != "LOG") + std::cout << "[" << level.toStdString() << "] "; + std::cout << message.toStdString() << std::endl; +} diff --git a/StoneIsland/plugins/cordova-plugin-console/src/ubuntu/console.h b/StoneIsland/plugins/cordova-plugin-console/src/ubuntu/console.h new file mode 100644 index 00000000..3f3d1634 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/src/ubuntu/console.h @@ -0,0 +1,43 @@ +/* + * Licensed 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 CONSOLE_H_FDSVCXGFRS +#define CONSOLE_H_FDSVCXGFRS + +#include <cplugin.h> + +#include <QtCore> + +class Console : public CPlugin { + Q_OBJECT +public: + explicit Console(Cordova *cordova); + + virtual const QString fullName() override { + return Console::fullID(); + } + + virtual const QString shortName() override { + return "Console"; + } + + static const QString fullID() { + return "Console"; + } + +public slots: + void logLevel(int scId, int ecId, QString level, QString message); +}; + +#endif diff --git a/StoneIsland/plugins/cordova-plugin-console/src/wp/DebugConsole.cs b/StoneIsland/plugins/cordova-plugin-console/src/wp/DebugConsole.cs new file mode 100644 index 00000000..9bb5476d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/src/wp/DebugConsole.cs @@ -0,0 +1,47 @@ +/* + Licensed 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. +*/ + +using System; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; +using System.Diagnostics; + +namespace WPCordovaClassLib.Cordova.Commands +{ + public class DebugConsole : BaseCommand + { + public void logLevel(string options) + { + string[] args = JSON.JsonHelper.Deserialize<string[]>(options); + string level = args[0]; + string msg = args[1]; + + if (level.Equals("LOG")) + { + Debug.WriteLine(msg); + } + else + { + Debug.WriteLine(level + ": " + msg); + } + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-console/tests/plugin.xml b/StoneIsland/plugins/cordova-plugin-console/tests/plugin.xml new file mode 100644 index 00000000..a44db3bc --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/tests/plugin.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + xmlns:rim="http://www.blackberry.com/ns/widgets" + xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-console-tests" + version="1.0.1"> + <name>Cordova Console Plugin Tests</name> + <license>Apache 2.0</license> + + <js-module src="tests.js" name="tests"> + </js-module> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-console/tests/tests.js b/StoneIsland/plugins/cordova-plugin-console/tests/tests.js new file mode 100644 index 00000000..6479e41d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/tests/tests.js @@ -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. + * +*/ + +exports.defineAutoTests = function () { + describe("Console", function () { + it("console.spec.1 should exist", function() { + expect(window.console).toBeDefined(); + }); + + it("console.spec.2 has required methods log|warn|error", function(){ + expect(window.console.log).toBeDefined(); + expect(typeof window.console.log).toBe('function'); + + expect(window.console.warn).toBeDefined(); + expect(typeof window.console.warn).toBe('function'); + + expect(window.console.error).toBeDefined(); + expect(typeof window.console.error).toBe('function'); + + }); + + }); +}; + +exports.defineManualTests = function (contentEl, createActionButton) {}; diff --git a/StoneIsland/plugins/cordova-plugin-console/www/console-via-logger.js b/StoneIsland/plugins/cordova-plugin-console/www/console-via-logger.js new file mode 100644 index 00000000..4095eb3e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/www/console-via-logger.js @@ -0,0 +1,187 @@ +/* + * + * 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("./logger"); +var utils = require("cordova/utils"); + +//------------------------------------------------------------------------------ +// 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/StoneIsland/plugins/cordova-plugin-console/www/logger.js b/StoneIsland/plugins/cordova-plugin-console/www/logger.js new file mode 100644 index 00000000..cbf81b9c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-console/www/logger.js @@ -0,0 +1,355 @@ +/* + * + * 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 utils = require('cordova/utils'); + +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/StoneIsland/plugins/cordova-plugin-device/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-device/CONTRIBUTING.md new file mode 100644 index 00000000..f7dbcaba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-device/LICENSE b/StoneIsland/plugins/cordova-plugin-device/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/NOTICE b/StoneIsland/plugins/cordova-plugin-device/NOTICE new file mode 100644 index 00000000..8ec56a52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/StoneIsland/plugins/cordova-plugin-device/README.md b/StoneIsland/plugins/cordova-plugin-device/README.md new file mode 100644 index 00000000..d3d7673d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/README.md @@ -0,0 +1,220 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +This plugin defines a global `device` object, which describes the device's hardware and software. +Although the object is in the global scope, it is not available until after the `deviceready` event. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + +## Installation + + cordova plugin add cordova-plugin-device + +## Properties + +- device.cordova +- device.model +- device.platform +- device.uuid +- device.version + +## device.cordova + +Get the version of Cordova running on the device. + +### Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Browser +- Firefox OS +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 + +## device.model + +The `device.model` returns the name of the device's model or +product. The value is set by the device manufacturer and may be +different across versions of the same product. + +### Supported Platforms + +- Android +- BlackBerry 10 +- Browser +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 + +### Quick Example + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models + // + var model = device.model; + +### Android Quirks + +- Gets the [product name](http://developer.android.com/reference/android/os/Build.html#PRODUCT) instead of the [model name](http://developer.android.com/reference/android/os/Build.html#MODEL), which is often the production code name. For example, the Nexus One returns `Passion`, and Motorola Droid returns `voles`. + +### Tizen Quirks + +- Returns the device model assigned by the vendor, for example, `TIZEN` + +### Windows Phone 7 and 8 Quirks + +- Returns the device model specified by the manufacturer. For example, the Samsung Focus returns `SGH-i917`. + +## device.platform + +Get the device's operating system name. + + var string = device.platform; + +### Supported Platforms + +- Android +- BlackBerry 10 +- Browser4 +- Firefox OS +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 + +### Quick Example + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + +### Windows Phone 7 Quirks + +Windows Phone 7 devices report the platform as `WinCE`. + +### Windows Phone 8 Quirks + +Windows Phone 8 devices report the platform as `Win32NT`. + +## device.uuid + +Get the device's Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). + + var string = device.uuid; + +### Description + +The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model. + +### Supported Platforms + +- Android +- BlackBerry 10 +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 + +### Quick Example + + // Android: Returns a random 64-bit integer (as a string, again!) + // The integer is generated on the device's first boot + // + // BlackBerry: Returns the PIN number of the device + // This is a nine-digit unique integer (as a string, though!) + // + // iPhone: (Paraphrased from the UIDevice Class documentation) + // Returns a string of hash values created from multiple hardware identifies. + // It is guaranteed to be unique for every device and can't be tied + // to the user account. + // Windows Phone 7 : Returns a hash of device+current user, + // if the user is not defined, a guid is generated and will persist until the app is uninstalled + // Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number + // unique to every GSM and UMTS mobile phone. + var deviceID = device.uuid; + +### iOS Quirk + +The `uuid` on iOS is not unique to a device, but varies for each +application, for each installation. It changes if you delete and +re-install the app, and possibly also when you upgrade iOS, or even +upgrade the app per version (apparent in iOS 5.1). The `uuid` is not +a reliable value. + +### Windows Phone 7 and 8 Quirks + +The `uuid` for Windows Phone 7 requires the permission +`ID_CAP_IDENTITY_DEVICE`. Microsoft will likely deprecate this +property soon. If the capability is not available, the application +generates a persistent guid that is maintained for the duration of the +application's installation on the device. + +## device.version + +Get the operating system version. + + var string = device.version; + +### Supported Platforms + +- Android 2.1+ +- BlackBerry 10 +- Browser +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 + +### Quick Example + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; + diff --git a/StoneIsland/plugins/cordova-plugin-device/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-device/RELEASENOTES.md new file mode 100644 index 00000000..f06fc6b5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/RELEASENOTES.md @@ -0,0 +1,114 @@ +<!-- +# +# 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. +# +--> +# Release Notes + +### 0.2.1 (Sept 5, 2013) +* removed extraneous print statement +* [CB-4432] copyright notice change + +### 0.2.3 (Sept 25, 2013) +* CB-4889 bumping&resetting version +* [windows8] commandProxy has moved +* [BlackBerry10] removed uneeded permission tags in plugin.xml +* CB-4889 renaming org.apache.cordova.core.device to org.apache.cordova.device +* Rename CHANGELOG.md -> RELEASENOTES.md +* updated to use commandProxy for ffos +* add firefoxos support +* [CB-4752] Incremented plugin version on dev branch. + +### 0.2.4 (Oct 28, 2013) +* CB-5128: added repo + issue tag in plugin.xml for device plugin +* CB-5085 device.cordova returning wrong value +* [CB-4915] Incremented plugin version on dev branch. + +### 0.2.5 (Dec 4, 2013) +* CB-5316 Spell Cordova as a brand unless it's a command or script +* [ubuntu] use cordova/exec/proxy +* add ubuntu platform +* Modify Device.platform logic to use amazon-fireos as the platform for Amazon Devices +* 1. Added amazon-fireos platform. 2. Change to use cordova-amazon-fireos as the platform if user agent contains 'cordova-amazon-fireos' + +### 0.2.6 (Jan 02, 2014) +* CB-5658 Add doc/index.md for Device plugin +* CB-5504 Moving Telephony Logic out of Device + +### 0.2.7 (Jan 07, 2014) +* CB-5737 Fix exception on close caused by left over telephony code from CB-5504 + +### 0.2.8 (Feb 05, 2014) +* Tizen support added + +### 0.2.9 (Apr 17, 2014) +* CB-5105: [Android, windows8, WP, BlackBerry10] Removed dead code for device.version +* CB-6422: [windows8] use cordova/exec/proxy +* CB-6460: Update license headers +* Add NOTICE file + +### 0.2.10 (Jun 05, 2014) +* CB-6127 Spanish and French Translations added. Github close #12 +* Changing 1.5 to 2.0 +* added firefoxos version - conversion +* added firefoxos version +* CB-6800 Add license +* CB-6491 add CONTRIBUTING.md + +### 0.2.11 (Aug 06, 2014) +* [FFOS] update DeviceProxy.js +* CB-6127 Updated translations for docs +* Use Windows system calls to get better info + +### 0.2.12 (Sep 17, 2014) +* CB-7471 cordova-plugin-device documentation translation +* CB-7552 device.name docs have not been removed +* [fxos] Fix cordova version +* added status box and documentation to manual tests +* [fxos] Fix cordova version +* added status box and documentation to manual tests +* Added plugin support for the browser +* CB-7262 Adds support for universal windows apps. + +### 0.2.13 (Dec 02, 2014) +* Changing `device.platform` to always report the platform as "browser". +* CB-5892 - Remove deprecated `window.Settings` +* CB-7700 cordova-plugin-device documentation translation: cordova-plugin-device +* CB-7571 Bump version of nested plugin to match parent plugin + +### 0.3.0 (Feb 04, 2015) +* Added device.manufacturer property for Android, iOS, Blackberry, WP8 +* Support for Windows Phone 8 ANID2 ANID is only supported up to Windows Phone 7.5 +* CB-8351 Use a local copy of uniqueAppInstanceIdentifier rather than CordovaLib's version +* browser: Fixed a bug that caused an "cannot call method of undefined" error if the browser's user agent wasn't recognized + +### 1.0.0 (Apr 15, 2015) +* CB-8746 gave plugin major version bump +* CB-8683 changed plugin-id to pacakge-name +* CB-8653 properly updated translated docs to use new id +* CB-8653 updated translated docs to use new id +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* CB-8653 Updated Readme +* remove defunct windows8 version +* add travis badge +* Add cross-plugin ios paramedic test running for TravisCI +* CB-8538 Added package.json file + +### 1.0.1 (Jun 17, 2015) +* CB-9128 cordova-plugin-device documentation translation: cordova-plugin-device +* Attempts to corrent npm markdown issue diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/de/README.md new file mode 100644 index 00000000..81f89e99 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/de/README.md @@ -0,0 +1,203 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +Dieses Plugin definiert eine globale `device` -Objekt, das des Geräts Hard- und Software beschreibt. Das Objekt im globalen Gültigkeitsbereich ist es zwar nicht verfügbar bis nach dem `deviceready` Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Installation + + cordova plugin add cordova-plugin-device + + +## Eigenschaften + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +Rufen Sie die Version von Cordova, die auf dem Gerät ausgeführt. + +### Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Browser + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + +## device.model + +Die `device.model` gibt den Namen der Modell- oder des Geräts zurück. Der Wert wird vom Gerätehersteller festgelegt und kann zwischen den Versionen des gleichen Produkts unterschiedlich sein. + +### Unterstützte Plattformen + + * Android + * BlackBerry 10 + * Browser + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + +### Kurzes Beispiel + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Finden Sie unter http://theiphonewiki.com/wiki/index.php?title=Models / / Var-Modell = device.model; + + +### Android Eigenarten + + * Ruft den [Produktname](http://developer.android.com/reference/android/os/Build.html#PRODUCT) anstelle des [Modellnamens](http://developer.android.com/reference/android/os/Build.html#MODEL), das ist oft der Codename für die Produktion. Beispielsweise das Nexus One gibt `Passion` , und Motorola Droid gibt`voles`. + +### Tizen Macken + + * Gibt z. B. das Gerätemodell von dem Kreditor zugeordnet,`TIZEN` + +### Windows Phone 7 und 8 Eigenarten + + * Gibt das vom Hersteller angegebenen Gerätemodell zurück. Beispielsweise gibt der Samsung-Fokus`SGH-i917`. + +## device.platform + +Name des Betriebssystems des Geräts zu erhalten. + + var string = device.platform; + + +### Unterstützte Plattformen + + * Android + * BlackBerry 10 + * Browser4 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + +### Kurzes Beispiel + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 Macken + +Windows Phone 7 Geräte melden die Plattform als`WinCE`. + +### Windows Phone 8 Macken + +Windows Phone 8 Geräte melden die Plattform als`Win32NT`. + +## device.uuid + +Des Geräts Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) zu erhalten). + + var string = device.uuid; + + +### Beschreibung + +Die Details wie eine UUID generiert wird werden vom Gerätehersteller und beziehen sich auf die Plattform oder das Modell des Geräts. + +### Unterstützte Plattformen + + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + +### Kurzes Beispiel + + / / Android: wird eine zufällige 64-Bit-Ganzzahl (als Zeichenfolge, wieder!) / / die ganze Zahl wird beim ersten Start des Geräts erzeugt / / / / BlackBerry: gibt die PIN-Nummer des Gerätes / / Dies ist eine neunstellige eindeutige Ganzzahl (als String, obwohl!) / / / / iPhone: (paraphrasiert aus der Dokumentation zur UIDevice-Klasse) / / liefert eine Reihe von Hash-Werte, die aus mehreren Hardware erstellt identifiziert. + / / Es ist gewährleistet, dass für jedes Gerät eindeutig sein und kann nicht gebunden werden / / an den Benutzer weitergeleitet. + / / Windows Phone 7: gibt einen Hash des Gerät + aktueller Benutzer, / / wenn der Benutzer nicht definiert ist, eine Guid generiert und wird weiter bestehen, bis die app deinstalliert wird / / Tizen: gibt das Gerät IMEI (International Mobile Equipment Identity oder IMEI ist eine Zahl / / einzigartig für jedes GSM- und UMTS-Handy. + var deviceID = device.uuid; + + +### iOS Quirk + +Die `uuid` auf iOS ist nicht eindeutig zu einem Gerät, aber für jede Anwendung, für jede Installation variiert. Es ändert sich, wenn Sie löschen und neu die app installieren, und möglicherweise auch beim iOS zu aktualisieren, oder auch ein Upgrade möglich die app pro Version (scheinbaren in iOS 5.1). Die `uuid` ist kein zuverlässiger Wert. + +### Windows Phone 7 und 8 Eigenarten + +Die `uuid` für Windows Phone 7 die Berechtigung erfordert `ID_CAP_IDENTITY_DEVICE` . Microsoft wird diese Eigenschaft wahrscheinlich bald abzuschaffen. Wenn die Funktion nicht verfügbar ist, generiert die Anwendung eine persistente Guid, die für die Dauer der Installation der Anwendung auf dem Gerät gewährleistet ist. + +## device.version + +Version des Betriebssystems zu erhalten. + + var string = device.version; + + +### Unterstützte Plattformen + + * Android 2.1 + + * BlackBerry 10 + * Browser + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + +### Kurzes Beispiel + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/de/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/de/index.md new file mode 100644 index 00000000..e3a537ed --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/de/index.md @@ -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. +--> + +# cordova-plugin-device + +Dieses Plugin definiert eine globale `device` -Objekt, das des Geräts Hard- und Software beschreibt. Das Objekt im globalen Gültigkeitsbereich ist es zwar nicht verfügbar bis nach dem `deviceready` Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Installation + + cordova plugin add cordova-plugin-device + + +## Eigenschaften + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +Rufen Sie die Version von Cordova, die auf dem Gerät ausgeführt. + +### Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Browser +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +## device.model + +Die `device.model` gibt den Namen der Modell- oder des Geräts zurück. Der Wert wird vom Gerätehersteller festgelegt und kann zwischen den Versionen des gleichen Produkts unterschiedlich sein. + +### Unterstützte Plattformen + +* Android +* BlackBerry 10 +* Browser +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +### Kurzes Beispiel + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Finden Sie unter http://theiphonewiki.com/wiki/index.php?title=Models / / Var-Modell = device.model; + + +### Android Eigenarten + +* Ruft den [Produktname][1] anstelle des [Modellnamens][2], das ist oft der Codename für die Produktion. Beispielsweise das Nexus One gibt `Passion` , und Motorola Droid gibt`voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### Tizen Macken + +* Gibt z. B. das Gerätemodell von dem Kreditor zugeordnet,`TIZEN` + +### Windows Phone 7 und 8 Eigenarten + +* Gibt das vom Hersteller angegebenen Gerätemodell zurück. Beispielsweise gibt der Samsung-Fokus`SGH-i917`. + +## device.platform + +Name des Betriebssystems des Geräts zu erhalten. + + var string = device.platform; + + +### Unterstützte Plattformen + +* Android +* BlackBerry 10 +* Browser4 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +### Kurzes Beispiel + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 Macken + +Windows Phone 7 Geräte melden die Plattform als`WinCE`. + +### Windows Phone 8 Macken + +Windows Phone 8 Geräte melden die Plattform als`Win32NT`. + +## device.uuid + +Des Geräts Universally Unique Identifier ([UUID][3] zu erhalten). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### Beschreibung + +Die Details wie eine UUID generiert wird werden vom Gerätehersteller und beziehen sich auf die Plattform oder das Modell des Geräts. + +### Unterstützte Plattformen + +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +### Kurzes Beispiel + + / / Android: wird eine zufällige 64-Bit-Ganzzahl (als Zeichenfolge, wieder!) / / die ganze Zahl wird beim ersten Start des Geräts erzeugt / / / / BlackBerry: gibt die PIN-Nummer des Gerätes / / Dies ist eine neunstellige eindeutige Ganzzahl (als String, obwohl!) / / / / iPhone: (paraphrasiert aus der Dokumentation zur UIDevice-Klasse) / / liefert eine Reihe von Hash-Werte, die aus mehreren Hardware erstellt identifiziert. + / / Es ist gewährleistet, dass für jedes Gerät eindeutig sein und kann nicht gebunden werden / / an den Benutzer weitergeleitet. + / / Windows Phone 7: gibt einen Hash des Gerät + aktueller Benutzer, / / wenn der Benutzer nicht definiert ist, eine Guid generiert und wird weiter bestehen, bis die app deinstalliert wird / / Tizen: gibt das Gerät IMEI (International Mobile Equipment Identity oder IMEI ist eine Zahl / / einzigartig für jedes GSM- und UMTS-Handy. + var deviceID = device.uuid; + + +### iOS Quirk + +Die `uuid` auf iOS ist nicht eindeutig zu einem Gerät, aber für jede Anwendung, für jede Installation variiert. Es ändert sich, wenn Sie löschen und neu die app installieren, und möglicherweise auch beim iOS zu aktualisieren, oder auch ein Upgrade möglich die app pro Version (scheinbaren in iOS 5.1). Die `uuid` ist kein zuverlässiger Wert. + +### Windows Phone 7 und 8 Eigenarten + +Die `uuid` für Windows Phone 7 die Berechtigung erfordert `ID_CAP_IDENTITY_DEVICE` . Microsoft wird diese Eigenschaft wahrscheinlich bald abzuschaffen. Wenn die Funktion nicht verfügbar ist, generiert die Anwendung eine persistente Guid, die für die Dauer der Installation der Anwendung auf dem Gerät gewährleistet ist. + +## device.version + +Version des Betriebssystems zu erhalten. + + var string = device.version; + + +### Unterstützte Plattformen + +* Android 2.1 + +* BlackBerry 10 +* Browser +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +### Kurzes Beispiel + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/es/README.md new file mode 100644 index 00000000..a27abfb8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/es/README.md @@ -0,0 +1,216 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +Este plugin define un global `device` objeto que describe del dispositivo hardware y software. Aunque el objeto está en el ámbito global, no está disponible hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Instalación + + cordova plugin add cordova-plugin-device + + +## Propiedades + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +Obtener la versión de Cordova que se ejecuta en el dispositivo. + +### Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Explorador + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + +## device.model + +El `device.model` devuelve el nombre de modelo del dispositivo o producto. El valor es fijado por el fabricante del dispositivo y puede ser diferente a través de versiones del mismo producto. + +### Plataformas soportadas + + * Android + * BlackBerry 10 + * Explorador + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + +### Ejemplo rápido + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models + // + var model = device.model; + + +### Rarezas Android + + * Obtiene el [nombre del producto](http://developer.android.com/reference/android/os/Build.html#PRODUCT) en lugar del [nombre de la modelo](http://developer.android.com/reference/android/os/Build.html#MODEL), que es a menudo el nombre de código de producción. Por ejemplo, el Nexus One devuelve `Passion` y Motorola Droid devuelve `voles`. + +### Rarezas Tizen + + * Devuelve que el modelo de dispositivo asignado por el proveedor, por ejemplo, `TIZEN` + +### Windows Phone 7 y 8 rarezas + + * Devuelve el modelo de dispositivo especificado por el fabricante. Por ejemplo, el Samsung Focus devuelve `SGH-i917`. + +## device.platform + +Obtener el nombre del sistema operativo del dispositivo. + + var string = device.platform; + + +### Plataformas soportadas + + * Android + * BlackBerry 10 + * Browser4 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + +### Ejemplo rápido + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 rarezas + +Dispositivos Windows Phone 7 informe de la plataforma como `WinCE`. + +### Windows Phone 8 rarezas + +Dispositivos Windows Phone 8 Informe la plataforma como `Win32NT`. + +## device.uuid + +Obtener identificador universalmente única del dispositivo ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). + + var string = device.uuid; + + +### Descripción + +Los detalles de cómo se genera un UUID son determinados por el fabricante del dispositivo y son especÃficos a la plataforma del dispositivo o modelo. + +### Plataformas soportadas + + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + +### Ejemplo rápido + + // Android: Returns a random 64-bit integer (as a string, again!) + // The integer is generated on the device's first boot + // + // BlackBerry: Returns the PIN number of the device + // This is a nine-digit unique integer (as a string, though!) + // + // iPhone: (Paraphrased from the UIDevice Class documentation) + // Returns a string of hash values created from multiple hardware identifies. + // It is guaranteed to be unique for every device and can't be tied + // to the user account. + // Windows Phone 7 : Returns a hash of device+current user, + // if the user is not defined, a guid is generated and will persist until the app is uninstalled + // Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number + // unique to every GSM and UMTS mobile phone. + var deviceID = device.uuid; + + +### Rarezas de iOS + +El `uuid` en iOS no es exclusiva de un dispositivo, pero varÃa para cada aplicación, para cada instalación. Cambia si puedes borrar y volver a instalar la aplicación, y posiblemente también cuándo actualizar iOS, o incluso mejorar la aplicación por la versión (evidente en iOS 5.1). El `uuid` no es un valor confiable. + +### Windows Phone 7 y 8 rarezas + +El `uuid` para Windows Phone 7 requiere el permiso `ID_CAP_IDENTITY_DEVICE`. Microsoft pronto probablemente desaprueban esta propiedad. Si la capacidad no está disponible, la aplicación genera un guid persistente que se mantiene durante la duración de la instalación de la aplicación en el dispositivo. + +## device.version + +Obtener la versión del sistema operativo. + + var string = device.version; + + +### Plataformas soportadas + + * Android 2.1 + + * BlackBerry 10 + * Explorador + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + +### Ejemplo rápido + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/es/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/es/index.md new file mode 100644 index 00000000..f4a58977 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/es/index.md @@ -0,0 +1,220 @@ +<!--- + 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-plugin-device + +Este plugin define un global `device` objeto que describe del dispositivo hardware y software. Aunque el objeto está en el ámbito global, no está disponible hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Instalación + + cordova plugin add cordova-plugin-device + + +## Propiedades + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +Obtener la versión de Cordova que se ejecuta en el dispositivo. + +### Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Explorador +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +## device.model + +El `device.model` devuelve el nombre de modelo del dispositivo o producto. El valor es fijado por el fabricante del dispositivo y puede ser diferente a través de versiones del mismo producto. + +### Plataformas soportadas + +* Android +* BlackBerry 10 +* Explorador +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +### Ejemplo rápido + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models + // + var model = device.model; + + +### Rarezas Android + +* Obtiene el [nombre del producto][1] en lugar del [nombre de la modelo][2], que es a menudo el nombre de código de producción. Por ejemplo, el Nexus One devuelve `Passion` y Motorola Droid devuelve `voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### Rarezas Tizen + +* Devuelve que el modelo de dispositivo asignado por el proveedor, por ejemplo, `TIZEN` + +### Windows Phone 7 y 8 rarezas + +* Devuelve el modelo de dispositivo especificado por el fabricante. Por ejemplo, el Samsung Focus devuelve `SGH-i917`. + +## device.platform + +Obtener el nombre del sistema operativo del dispositivo. + + var string = device.platform; + + +### Plataformas soportadas + +* Android +* BlackBerry 10 +* Browser4 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +### Ejemplo rápido + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 rarezas + +Dispositivos Windows Phone 7 informe de la plataforma como `WinCE`. + +### Windows Phone 8 rarezas + +Dispositivos Windows Phone 8 Informe la plataforma como `Win32NT`. + +## device.uuid + +Obtener identificador universalmente única del dispositivo ([UUID][3]). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### Descripción + +Los detalles de cómo se genera un UUID son determinados por el fabricante del dispositivo y son especÃficos a la plataforma del dispositivo o modelo. + +### Plataformas soportadas + +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +### Ejemplo rápido + + // Android: devuelve un entero de 64 bits al azar (como una cadena, otra vez!) + // el entero es generado en el primer arranque del dispositivo + // + // BlackBerry: devuelve el número PIN del dispositivo + // este es un entero único de nueve dÃgitos (como una cadena, aunque!) + // + // iPhone: (parafraseado de la documentación de la clase UIDevice) + // devuelve una cadena de valores hash creado a partir + // de múltiples hardware identifica. + / / Está garantizado para ser único para cada dispositivo y no puede ser atado / / a la cuenta de usuario. + // Windows Phone 7: devuelve un hash de dispositivo + usuario actual, + // si el usuario no está definido, un guid generado y persistirá hasta que se desinstala la aplicación + // + // Tizen: devuelve el dispositivo IMEI (identidad de equipo móvil internacional o IMEI es un número + // único para cada teléfono móvil GSM y UMTS. + var deviceID = device.uuid; + + +### iOS chanfle + +El `uuid` en iOS no es exclusiva de un dispositivo, pero varÃa para cada aplicación, para cada instalación. Cambia si puedes borrar y volver a instalar la aplicación, y posiblemente también cuándo actualizar iOS, o incluso mejorar la aplicación por la versión (evidente en iOS 5.1). El `uuid` no es un valor confiable. + +### Windows Phone 7 y 8 rarezas + +El `uuid` para Windows Phone 7 requiere el permiso `ID_CAP_IDENTITY_DEVICE`. Microsoft pronto probablemente desaprueban esta propiedad. Si la capacidad no está disponible, la aplicación genera un guid persistente que se mantiene durante la duración de la instalación de la aplicación en el dispositivo. + +## device.version + +Obtener la versión del sistema operativo. + + var string = device.version; + + +### Plataformas soportadas + +* Android 2.1 + +* BlackBerry 10 +* Explorador +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +### Ejemplo rápido + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. el Mango se vuelve 7.10.7720 + // Tizen: devuelve "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/fr/README.md new file mode 100644 index 00000000..4101fd94 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/fr/README.md @@ -0,0 +1,215 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +Ce plugin définit un global `device` objet qui décrit le matériel et les logiciels de l'appareil. Bien que l'objet est dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Installation + + cordova plugin add cordova-plugin-device + + +## Propriétés + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +Retourne la version de Cordova en cours d'exécution sur l'appareil. + +### Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Navigateur + * Firefox OS + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + +## device.model + +L'objet `device.model` retourne le nom du modèle de l'appareil/produit. Cette valeur est définie par le fabricant du périphérique et peut varier entre les différentes versions d'un même produit. + +### Plates-formes supportées + + * Android + * BlackBerry 10 + * Navigateur + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + +### Exemple court + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Voir http://theiphonewiki.com/wiki/index.php?title=Models + // + var model = device.model; + + +### Quirks Android + + * Retourne le [nom du produit](http://developer.android.com/reference/android/os/Build.html#PRODUCT) au lieu du [nom du modèle](http://developer.android.com/reference/android/os/Build.html#MODEL), ce qui équivaut souvent au nom de code de production. Par exemple, `Passion` pour le Nexus One et `voles` pour le Motorola Droid. + +### Bizarreries de paciarelli + + * Retourne le modèle du dispositif, assigné par le vendeur, par exemple `TIZEN` + +### Notes au sujet de Windows Phone 7 et 8 + + * Retourne le modèle de l'appareil spécifié par le fabricant. Par exemple `SGH-i917` pour le Samsung Focus. + +## device.platform + +Obtenir le nom de système d'exploitation de l'appareil. + + var string = device.platform; + + +### Plates-formes supportées + + * Android + * BlackBerry 10 + * Browser4 + * Firefox OS + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + +### Exemple court + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 Quirks + +Appareils Windows Phone 7 rapport de la plate-forme comme`WinCE`. + +### Notes au sujet de Windows Phone 8 + +Appareils Windows Phone 8 rapport de la plate-forme comme`Win32NT`. + +## device.uuid + +Obtenir Universally Unique Identifier de l'appareil ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). + + var string = device.uuid; + + +### Description + +Les détails de comment un UUID généré sont déterminées par le fabricant du périphérique et sont spécifiques à la plate-forme ou le modèle de l'appareil. + +### Plates-formes supportées + + * Android + * BlackBerry 10 + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + +### Exemple court + + // Android : retourne un nombre entier 64-bit aléatoire (sous la forme d'une chaîne de caractères, encore !) + // Ce nombre entier est généré lors du premier démarrage de l'appareil + // + // BlackBerry : retourne le numéro PIN de l'appareil + // Il s'agit d'un nombre entier unique à neuf chiffres (sous la forme d'une chaîne de caractères cependant !) + // + // iPhone : (copié depuis la documentation de la classe UIDevice) + // Retourne une chaîne de caractères générée à partir de plusieurs caractéristiques matérielles. + / / Il est garanti pour être unique pour chaque appareil et ne peut pas être lié / / pour le compte d'utilisateur. + // Windows Phone 7 : retourne un hashage généré à partir de appareil+utilisateur actuel, + // si aucun utilisateur n'est défini, un guid est généré persistera jusqu'à ce que l'application soit désinstallée + // Tizen : retourne le numéro IMEI (International Mobile Equipment Identity) de l'appareil, ce numéro est + // unique pour chaque téléphone GSM et UMTS. + var deviceID = device.uuid; + + +### Spécificités iOS + +Le `uuid` sur iOS n'est pas propre à un périphérique, mais varie pour chaque application, pour chaque installation. Elle change si vous supprimez, puis réinstallez l'application, et éventuellement aussi quand vous mettre à jour d'iOS, ou même mettre à jour le soft par version (apparent dans iOS 5.1). Le `uuid` n'est pas une valeur fiable. + +### Notes au sujet de Windows Phone 7 et 8 + +Le `uuid` pour Windows Phone 7 requiert l'autorisation `ID_CAP_IDENTITY_DEVICE` . Microsoft va probablement bientôt obsolète de cette propriété. Si la capacité n'est pas disponible, l'application génère un guid persistant qui est maintenu pendant toute la durée de l'installation de l'application sur le périphérique. + +## device.version + +Téléchargez la version de système d'exploitation. + + var string = device.version; + + +### Plates-formes supportées + + * Android 2.1+ + * BlackBerry 10 + * Navigateur + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + +### Exemple court + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/fr/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/fr/index.md new file mode 100644 index 00000000..163e498c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/fr/index.md @@ -0,0 +1,218 @@ +<!--- + 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-plugin-device + +Ce plugin définit un global `device` objet qui décrit le matériel et les logiciels de l'appareil. Bien que l'objet est dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Installation + + cordova plugin add cordova-plugin-device + + +## Propriétés + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +Retourne la version de Cordova en cours d'exécution sur l'appareil. + +### Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Navigateur +* Firefox OS +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +## device.model + +L'objet `device.model` retourne le nom du modèle de l'appareil/produit. Cette valeur est définie par le fabricant du périphérique et peut varier entre les différentes versions d'un même produit. + +### Plates-formes prises en charge + +* Android +* BlackBerry 10 +* Navigateur +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +### Petit exemple + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Voir http://theiphonewiki.com/wiki/index.php?title=Models + // + var model = device.model; + + +### Quirks Android + +* Retourne le [nom du produit][1] au lieu du [nom du modèle][2], ce qui équivaut souvent au nom de code de production. Par exemple, `Passion` pour le Nexus One et `voles` pour le Motorola Droid. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### Bizarreries de paciarelli + +* Retourne le modèle du dispositif, assigné par le vendeur, par exemple `TIZEN` + +### Windows Phone 7 et 8 Quirks + +* Retourne le modèle de l'appareil spécifié par le fabricant. Par exemple `SGH-i917` pour le Samsung Focus. + +## device.platform + +Obtenir le nom de système d'exploitation de l'appareil. + + var string = device.platform; + + +### Plates-formes prises en charge + +* Android +* BlackBerry 10 +* Browser4 +* Firefox OS +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +### Petit exemple + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 Quirks + +Appareils Windows Phone 7 rapport de la plate-forme comme`WinCE`. + +### Notes au sujet de Windows Phone 8 + +Appareils Windows Phone 8 rapport de la plate-forme comme`Win32NT`. + +## device.uuid + +Obtenir Universally Unique Identifier de l'appareil ([UUID][3]). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### Description + +Les détails de comment un UUID généré sont déterminées par le fabricant du périphérique et sont spécifiques à la plate-forme ou le modèle de l'appareil. + +### Plates-formes prises en charge + +* Android +* BlackBerry 10 +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +### Petit exemple + + // Android : retourne un nombre entier 64-bit aléatoire (sous la forme d'une chaîne de caractères, encore !) + // Ce nombre entier est généré lors du premier démarrage de l'appareil + // + // BlackBerry : retourne le numéro PIN de l'appareil + // Il s'agit d'un nombre entier unique à neuf chiffres (sous la forme d'une chaîne de caractères cependant !) + // + // iPhone : (copié depuis la documentation de la classe UIDevice) + // Retourne une chaîne de caractères générée à partir de plusieurs caractéristiques matérielles. + / / Il est garanti pour être unique pour chaque appareil et ne peut pas être lié / / pour le compte d'utilisateur. + // Windows Phone 7 : retourne un hashage généré à partir de appareil+utilisateur actuel, + // si aucun utilisateur n'est défini, un guid est généré persistera jusqu'à ce que l'application soit désinstallée + // Tizen : retourne le numéro IMEI (International Mobile Equipment Identity) de l'appareil, ce numéro est + // unique pour chaque téléphone GSM et UMTS. + var deviceID = device.uuid; + + +### Spécificités iOS + +Le `uuid` sur iOS n'est pas propre à un périphérique, mais varie pour chaque application, pour chaque installation. Elle change si vous supprimez, puis réinstallez l'application, et éventuellement aussi quand vous mettre à jour d'iOS, ou même mettre à jour le soft par version (apparent dans iOS 5.1). Le `uuid` n'est pas une valeur fiable. + +### Windows Phone 7 et 8 Quirks + +Le `uuid` pour Windows Phone 7 requiert l'autorisation `ID_CAP_IDENTITY_DEVICE` . Microsoft va probablement bientôt obsolète de cette propriété. Si la capacité n'est pas disponible, l'application génère un guid persistant qui est maintenu pendant toute la durée de l'installation de l'application sur le périphérique. + +## device.version + +Téléchargez la version de système d'exploitation. + + var string = device.version; + + +### Plates-formes prises en charge + +* Android 2.1+ +* BlackBerry 10 +* Navigateur +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +### Petit exemple + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/it/README.md new file mode 100644 index 00000000..79749626 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/it/README.md @@ -0,0 +1,203 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +Questo plugin definisce un global `device` oggetto che descrive il dispositivo hardware e software. Sebbene l'oggetto sia in ambito globale, non è disponibile fino a dopo il `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Installazione + + cordova plugin add cordova-plugin-device + + +## Proprietà + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +Ottenere la versione di Cordova in esecuzione nel dispositivo. + +### Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Browser + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + +## device.model + +Il `device.model` restituisce il nome del modello del dispositivo o del prodotto. Il valore viene impostato dal produttore del dispositivo e può essere differente tra le versioni dello stesso prodotto. + +### Piattaforme supportate + + * Android + * BlackBerry 10 + * Browser + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + +### Esempio rapido + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Vedi http://theiphonewiki.com/wiki/index.php?title=Models / / modello var = device.model; + + +### Stranezze Android + + * Ottiene il [nome del prodotto](http://developer.android.com/reference/android/os/Build.html#PRODUCT) anziché il [nome del modello](http://developer.android.com/reference/android/os/Build.html#MODEL), che è spesso il nome di codice di produzione. Ad esempio, restituisce il Nexus One `Passion` , e Motorola Droid restituisce`voles`. + +### Tizen stranezze + + * Restituisce il modello di dispositivo assegnato dal fornitore, ad esempio,`TIZEN` + +### Windows Phone 7 e 8 stranezze + + * Restituisce il modello di dispositivo specificato dal produttore. Ad esempio, restituisce il Samsung Focus`SGH-i917`. + +## device.platform + +Ottenere il nome del sistema operativo del dispositivo. + + var string = device.platform; + + +### Piattaforme supportate + + * Android + * BlackBerry 10 + * Browser4 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + +### Esempio rapido + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 capricci + +Windows Phone 7 dispositivi segnalano la piattaforma come`WinCE`. + +### Windows Phone 8 stranezze + +Dispositivi Windows Phone 8 segnalano la piattaforma come`Win32NT`. + +## device.uuid + +Ottenere identificatore del dispositivo univoco universale ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). + + var string = device.uuid; + + +### Descrizione + +I dettagli di come viene generato un UUID sono determinati dal produttore del dispositivo e sono specifici per la piattaforma o il modello del dispositivo. + +### Piattaforme supportate + + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + +### Esempio rapido + + / / Android: restituisce un intero casuale di 64 bit (come stringa, ancora una volta!) / / il numero intero è generato al primo avvio del dispositivo / / / / BlackBerry: restituisce il numero PIN del dispositivo / / questo è un valore integer univoco a nove cifre (come stringa, benchè!) / / / / iPhone: (parafrasato dalla documentazione della classe UIDevice) / / restituisce una stringa di valori hash creata dall'hardware più identifica. + / / È garantito per essere unica per ogni dispositivo e non può essere legato / / per l'account utente. + / / Windows Phone 7: restituisce un hash dell'utente corrente, + dispositivo / / se l'utente non è definito, un guid generato e persisterà fino a quando l'applicazione viene disinstallata / / Tizen: restituisce il dispositivo IMEI (International Mobile Equipment Identity o IMEI è un numero / / unico per ogni cellulare GSM e UMTS. + var deviceID = device.uuid; + + +### iOS Quirk + +Il `uuid` su iOS non è univoco per un dispositivo, ma varia per ogni applicazione, per ogni installazione. Cambia se si elimina e re-installare l'app, e possibilmente anche quando aggiornare iOS o anche aggiornare l'app per ogni versione (apparente in iOS 5.1). Il `uuid` non è un valore affidabile. + +### Windows Phone 7 e 8 stranezze + +Il `uuid` per Windows Phone 7 richiede l'autorizzazione `ID_CAP_IDENTITY_DEVICE` . Microsoft probabilmente sarà presto deprecare questa proprietà . Se la funzionalità non è disponibile, l'applicazione genera un guid persistente che viene mantenuto per la durata dell'installazione dell'applicazione sul dispositivo. + +## device.version + +Ottenere la versione del sistema operativo. + + var string = device.version; + + +### Piattaforme supportate + + * Android 2.1 + + * BlackBerry 10 + * Browser + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + +### Esempio rapido + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/it/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/it/index.md new file mode 100644 index 00000000..98c6200a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/it/index.md @@ -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. +--> + +# cordova-plugin-device + +Questo plugin definisce un global `device` oggetto che descrive il dispositivo hardware e software. Sebbene l'oggetto sia in ambito globale, non è disponibile fino a dopo il `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Installazione + + cordova plugin add cordova-plugin-device + + +## Proprietà + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +Ottenere la versione di Cordova in esecuzione nel dispositivo. + +### Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Browser +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +## device.model + +Il `device.model` restituisce il nome del modello del dispositivo o del prodotto. Il valore viene impostato dal produttore del dispositivo e può essere differente tra le versioni dello stesso prodotto. + +### Piattaforme supportate + +* Android +* BlackBerry 10 +* Browser +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +### Esempio rapido + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Vedi http://theiphonewiki.com/wiki/index.php?title=Models / / modello var = device.model; + + +### Stranezze Android + +* Ottiene il [nome del prodotto][1] anziché il [nome del modello][2], che è spesso il nome di codice di produzione. Ad esempio, restituisce il Nexus One `Passion` , e Motorola Droid restituisce`voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### Tizen stranezze + +* Restituisce il modello di dispositivo assegnato dal fornitore, ad esempio,`TIZEN` + +### Windows Phone 7 e 8 stranezze + +* Restituisce il modello di dispositivo specificato dal produttore. Ad esempio, restituisce il Samsung Focus`SGH-i917`. + +## device.platform + +Ottenere il nome del sistema operativo del dispositivo. + + var string = device.platform; + + +### Piattaforme supportate + +* Android +* BlackBerry 10 +* Browser4 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +### Esempio rapido + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 capricci + +Windows Phone 7 dispositivi segnalano la piattaforma come`WinCE`. + +### Windows Phone 8 stranezze + +Dispositivi Windows Phone 8 segnalano la piattaforma come`Win32NT`. + +## device.uuid + +Ottenere identificatore del dispositivo univoco universale ([UUID][3]). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### Descrizione + +I dettagli di come viene generato un UUID sono determinati dal produttore del dispositivo e sono specifici per la piattaforma o il modello del dispositivo. + +### Piattaforme supportate + +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +### Esempio rapido + + / / Android: restituisce un intero casuale di 64 bit (come stringa, ancora una volta!) / / il numero intero è generato al primo avvio del dispositivo / / / / BlackBerry: restituisce il numero PIN del dispositivo / / questo è un valore integer univoco a nove cifre (come stringa, benchè!) / / / / iPhone: (parafrasato dalla documentazione della classe UIDevice) / / restituisce una stringa di valori hash creata dall'hardware più identifica. + / / È garantito per essere unica per ogni dispositivo e non può essere legato / / per l'account utente. + / / Windows Phone 7: restituisce un hash dell'utente corrente, + dispositivo / / se l'utente non è definito, un guid generato e persisterà fino a quando l'applicazione viene disinstallata / / Tizen: restituisce il dispositivo IMEI (International Mobile Equipment Identity o IMEI è un numero / / unico per ogni cellulare GSM e UMTS. + var deviceID = device.uuid; + + +### iOS Quirk + +Il `uuid` su iOS non è univoco per un dispositivo, ma varia per ogni applicazione, per ogni installazione. Cambia se si elimina e re-installare l'app, e possibilmente anche quando aggiornare iOS o anche aggiornare l'app per ogni versione (apparente in iOS 5.1). Il `uuid` non è un valore affidabile. + +### Windows Phone 7 e 8 stranezze + +Il `uuid` per Windows Phone 7 richiede l'autorizzazione `ID_CAP_IDENTITY_DEVICE` . Microsoft probabilmente sarà presto deprecare questa proprietà . Se la funzionalità non è disponibile, l'applicazione genera un guid persistente che viene mantenuto per la durata dell'installazione dell'applicazione sul dispositivo. + +## device.version + +Ottenere la versione del sistema operativo. + + var string = device.version; + + +### Piattaforme supportate + +* Android 2.1 + +* BlackBerry 10 +* Browser +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +### Esempio rapido + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/ja/README.md new file mode 100644 index 00000000..5a345f87 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/ja/README.md @@ -0,0 +1,203 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +ã“ã®ãƒ—ラグインをグãƒãƒ¼ãƒãƒ«å®šç¾©ã—ã¾ã™ `device` オブジェクトã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã¨ã‚½ãƒ•トウェアã«ã¤ã„ã¦èª¬æ˜Žã—ã¾ã™ã€‚ ãれã¯å¾Œã¾ã§åˆ©ç”¨å¯èƒ½ãªã‚ªãƒ–ジェクトãŒã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã¯ã€ `deviceready` イベント。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## インストール + + cordova plugin add cordova-plugin-device + + +## プãƒãƒ‘ティ + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +デãƒã‚¤ã‚¹ã§å®Ÿè¡Œã•れã¦ã„るコルドãƒã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * ブラウザー + * Firefox ã® OS + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + +## device.model + +`device.model`ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã¾ãŸã¯è£½å“ã®åå‰ã‚’è¿”ã—ã¾ã™ã€‚値ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦è¨å®šã•れã€åŒã˜è£½å“ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³é–“ã§ç•°ãªã‚‹å¯èƒ½æ€§ãŒã‚りã¾ã™ã€‚ + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * ブラウザー + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + +### ç°¡å˜ãªä¾‹ + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models ã‚’å‚ç…§ã—ã¦ãã ã•ã„//var モデル = device.model; + + +### Android ã®ç™– + + * 生産コードåã¯[モデルå](http://developer.android.com/reference/android/os/Build.html#MODEL)ã®ä»£ã‚りã«[製å“å](http://developer.android.com/reference/android/os/Build.html#PRODUCT)ã‚’å–å¾—ã—ã¾ã™ã€‚ ãŸã¨ãˆã°ã€ãƒã‚¯ã‚µã‚¹ 1 ã¤ã‚’è¿”ã—ã¾ã™ `Passion` ã€Motorola ã®ãƒ‰ãƒã‚¤ãƒ‰ã‚’è¿”ã—ã¾ã™`voles`. + +### Tizen ã®ç™– + + * ãŸã¨ãˆã°ã€ãƒ™ãƒ³ãƒ€ãƒ¼ã«ã‚ˆã£ã¦å‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¦ã„るデãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™`TIZEN` + +### Windows Phone 7 㨠8 ç™– + + * è£½é€ å…ƒã«ã‚ˆã£ã¦æŒ‡å®šã•れãŸãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™ã€‚ãŸã¨ãˆã°ã€ä¸‰æ˜Ÿãƒ•ォーカスを返ã—ã¾ã™`SGH-i917`. + +## device.platform + +デãƒã‚¤ã‚¹ã®ã‚ªãƒšãƒ¬ãƒ¼ãƒ†ã‚£ãƒ³ã‚° システムåã‚’å–å¾—ã—ã¾ã™ã€‚ + + var string = device.platform; + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * Browser4 + * Firefox ã® OS + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + +### ç°¡å˜ãªä¾‹ + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 ã®ç™– + +Windows Phone 7 デãƒã‚¤ã‚¹ã¨ãƒ—ãƒ©ãƒƒãƒˆãƒ•ã‚©ãƒ¼ãƒ ã‚’å ±å‘Šã—ã¾ã™ã€‚`WinCE`. + +### Windows Phone 8 ç™– + +Windows Phone 8 デãƒã‚¤ã‚¹ã¨ãƒ—ãƒ©ãƒƒãƒˆãƒ•ã‚©ãƒ¼ãƒ ã‚’å ±å‘Šã—ã¾ã™ã€‚`Win32NT`. + +## device.uuid + +デãƒã‚¤ã‚¹ã®ãƒ¦ãƒ‹ãƒãƒ¼ã‚µãƒ« ・ ユニークè˜åˆ¥å ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)ã‚’å–å¾—ã—ã¾ã™ã€‚). + + var string = device.uuid; + + +### 解説 + +UUID を生æˆã™ã‚‹æ–¹æ³•ã®è©³ç´°ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦æ±ºå®šã•れã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ—ラットフォームやモデルã«å›ºæœ‰ã§ã™ã€‚ + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + +### ç°¡å˜ãªä¾‹ + + //アンドãƒã‚¤ãƒ‰: ランダム㪠64 ãƒ“ãƒƒãƒˆã®æ•´æ•° (ã‚’æ–‡å—列ã¨ã—ã¦è¿”ã—ã¾ã™ã€å†ã³ ï¼ï¼‰/デãƒã‚¤ã‚¹ã®æœ€åˆã®èµ·å‹•時ã«ç”Ÿæˆã•れる整数/////ブラックベリー: デãƒã‚¤ã‚¹ã®ãƒ”ン番å·ã‚’è¿”ã—ã¾ã™//ã“れ㯠9 æ¡ã®ä¸€æ„ãªæ•´æ•° (ã‚’æ–‡å—列ã¨ã—ã¦ã‚‚ ï¼)////iPhone: (UIDevice クラスã®ãƒ‰ã‚ュメントã‹ã‚‰è¨€ã„æ›ãˆï¼‰//è˜åˆ¥è¤‡æ•°ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‹ã‚‰ä½œæˆã•れãŸãƒãƒƒã‚·ãƒ¥å€¤ã®æ–‡å—列を返ã—ã¾ã™ã€‚。 + //ãれã¯ã™ã¹ã¦ã®ãƒ‡ãƒã‚¤ã‚¹ã«å¯¾ã—ã¦ä¸€æ„ã§ã‚ã‚‹ã“ã¨ãŒä¿è¨¼ã•ã‚Œã€æŽ¥ç¶šã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“//ユーザー アカウント。 + //Windows Phone 7: デãƒã‚¤ã‚¹ + ç¾åœ¨ã®ãƒ¦ãƒ¼ã‚¶ãƒ¼ã®ãƒãƒƒã‚·ãƒ¥ã‚’è¿”ã—ã¾ã™//ユーザーãŒå®šç¾©ã•れã¦ã„ãªã„å ´åˆ guid ãŒç”Ÿæˆã•れã€ã‚¢ãƒ—リãŒã‚¢ãƒ³ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã•れるã¾ã§ä¿æŒã•れã¾ã™//Tizen: デãƒã‚¤ã‚¹ã® IMEI ã‚’è¿”ã—ã¾ã™ (国際モãƒã‚¤ãƒ«æ©Ÿå™¨ã‚¢ã‚¤ãƒ‡ãƒ³ãƒ†ã‚£ãƒ†ã‚£ã¾ãŸã¯ IMEI ã¯ç•ªå·ã§ã™//ã™ã¹ã¦ã® GSM ãŠã‚ˆã³ UMTS ã®æºå¸¯é›»è©±ã«å›ºæœ‰ã§ã™ã€‚ + var deviceID = device.uuid; + + +### iOS ã®æ°—ã¾ãれ + +`uuid`IOS ã§ã€ãƒ‡ãƒã‚¤ã‚¹ã«å›ºæœ‰ã§ã¯ãªã„インストールã”ã¨ã€ã‚¢ãƒ—リケーションã”ã¨ã«ç•°ãªã‚Šã¾ã™ã€‚ 削除ã€ã‚¢ãƒ—リをå†ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã—ãŸå ´åˆã«å¤‰æ›´ã¨å¤šåˆ†ã¾ãŸã¨ãアップグレード iOS ã®, ã¾ãŸã¯ã‚‚アップグレードã™ã‚‹ã‚¢ãƒ—リ (iOS ã® 5.1 ã§æ˜Žã‚‰ã‹ã«ï¼‰ ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã”ã¨ã€‚ `uuid`ã¯ä¿¡é ¼æ€§ã®é«˜ã„値ã§ã¯ã‚りã¾ã›ã‚“。 + +### Windows Phone 7 㨠8 ç™– + +`uuid`ã®ãŸã‚ã« Windows Phone 7 ã«ã¯ã€æ¨©é™ãŒå¿…è¦ã§ã™ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft ã¯ã™ãã«ã“ã®ãƒ—ãƒãƒ‘ティを廃æ¢ã—ã¦å¯èƒ½æ€§ãŒã‚りã¾ã™ã€‚ 機能ãŒåˆ©ç”¨ã§ããªã„å ´åˆã€ã‚¢ãƒ—リケーションã¯ãƒ‡ãƒã‚¤ã‚¹ã¸ã®ã‚¢ãƒ—リケーションã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã®æŒç¶šæœŸé–“ã®ãŸã‚ã«ä¿æŒã•れã¦ã„る永続的㪠guid を生æˆã—ã¾ã™ã€‚ + +## device.version + +オペレーティング システムã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ + + var string = device.version; + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * アンドãƒã‚¤ãƒ‰ 2.1 + + * ブラックベリー 10 + * ブラウザー + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + +### ç°¡å˜ãªä¾‹ + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/ja/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/ja/index.md new file mode 100644 index 00000000..b4030fd0 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/ja/index.md @@ -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. +--> + +# cordova-plugin-device + +ã“ã®ãƒ—ラグインをグãƒãƒ¼ãƒãƒ«å®šç¾©ã—ã¾ã™ `device` オブジェクトã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã¨ã‚½ãƒ•トウェアã«ã¤ã„ã¦èª¬æ˜Žã—ã¾ã™ã€‚ ãれã¯å¾Œã¾ã§åˆ©ç”¨å¯èƒ½ãªã‚ªãƒ–ジェクトãŒã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã¯ã€ `deviceready` イベント。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## インストール + + cordova plugin add cordova-plugin-device + + +## プãƒãƒ‘ティ + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +デãƒã‚¤ã‚¹ã§å®Ÿè¡Œã•れã¦ã„るコルドãƒã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* ブラウザー +* Firefox ã® OS +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +## device.model + +`device.model`ã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã¾ãŸã¯è£½å“ã®åå‰ã‚’è¿”ã—ã¾ã™ã€‚値ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦è¨å®šã•れã€åŒã˜è£½å“ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³é–“ã§ç•°ãªã‚‹å¯èƒ½æ€§ãŒã‚りã¾ã™ã€‚ + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* ブラウザー +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +### ç°¡å˜ãªä¾‹ + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models ã‚’å‚ç…§ã—ã¦ãã ã•ã„//var モデル = device.model; + + +### Android ã®ç™– + +* 生産コードåã¯[モデルå][1]ã®ä»£ã‚りã«[製å“å][2]ã‚’å–å¾—ã—ã¾ã™ã€‚ ãŸã¨ãˆã°ã€ãƒã‚¯ã‚µã‚¹ 1 ã¤ã‚’è¿”ã—ã¾ã™ `Passion` ã€Motorola ã®ãƒ‰ãƒã‚¤ãƒ‰ã‚’è¿”ã—ã¾ã™`voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#MODEL + [2]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + +### Tizen ã®ç™– + +* ãŸã¨ãˆã°ã€ãƒ™ãƒ³ãƒ€ãƒ¼ã«ã‚ˆã£ã¦å‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¦ã„るデãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™`TIZEN` + +### Windows Phone 7 㨠8 ç™– + +* è£½é€ å…ƒã«ã‚ˆã£ã¦æŒ‡å®šã•れãŸãƒ‡ãƒã‚¤ã‚¹ã®ãƒ¢ãƒ‡ãƒ«ã‚’è¿”ã—ã¾ã™ã€‚ãŸã¨ãˆã°ã€ä¸‰æ˜Ÿãƒ•ォーカスを返ã—ã¾ã™`SGH-i917`. + +## device.platform + +デãƒã‚¤ã‚¹ã®ã‚ªãƒšãƒ¬ãƒ¼ãƒ†ã‚£ãƒ³ã‚° システムåã‚’å–å¾—ã—ã¾ã™ã€‚ + + var string = device.platform; + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* Browser4 +* Firefox ã® OS +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +### ç°¡å˜ãªä¾‹ + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 ã®ç™– + +Windows Phone 7 デãƒã‚¤ã‚¹ã¨ãƒ—ãƒ©ãƒƒãƒˆãƒ•ã‚©ãƒ¼ãƒ ã‚’å ±å‘Šã—ã¾ã™ã€‚`WinCE`. + +### Windows Phone 8 ç™– + +Windows Phone 8 デãƒã‚¤ã‚¹ã¨ãƒ—ãƒ©ãƒƒãƒˆãƒ•ã‚©ãƒ¼ãƒ ã‚’å ±å‘Šã—ã¾ã™ã€‚`Win32NT`. + +## device.uuid + +デãƒã‚¤ã‚¹ã®ãƒ¦ãƒ‹ãƒãƒ¼ã‚µãƒ« ・ ユニークè˜åˆ¥å ([UUID][3]ã‚’å–å¾—ã—ã¾ã™ã€‚). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### 説明 + +UUID を生æˆã™ã‚‹æ–¹æ³•ã®è©³ç´°ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®è£½é€ å…ƒã«ã‚ˆã£ã¦æ±ºå®šã•れã€ãƒ‡ãƒã‚¤ã‚¹ã®ãƒ—ラットフォームやモデルã«å›ºæœ‰ã§ã™ã€‚ + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +### ç°¡å˜ãªä¾‹ + + //アンドãƒã‚¤ãƒ‰: ランダム㪠64 ãƒ“ãƒƒãƒˆã®æ•´æ•° (ã‚’æ–‡å—列ã¨ã—ã¦è¿”ã—ã¾ã™ã€å†ã³ ï¼ï¼‰/デãƒã‚¤ã‚¹ã®æœ€åˆã®èµ·å‹•時ã«ç”Ÿæˆã•れる整数/////ブラックベリー: デãƒã‚¤ã‚¹ã®ãƒ”ン番å·ã‚’è¿”ã—ã¾ã™//ã“れ㯠9 æ¡ã®ä¸€æ„ãªæ•´æ•° (ã‚’æ–‡å—列ã¨ã—ã¦ã‚‚ ï¼)////iPhone: (UIDevice クラスã®ãƒ‰ã‚ュメントã‹ã‚‰è¨€ã„æ›ãˆï¼‰//è˜åˆ¥è¤‡æ•°ã®ãƒãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‹ã‚‰ä½œæˆã•れãŸãƒãƒƒã‚·ãƒ¥å€¤ã®æ–‡å—列を返ã—ã¾ã™ã€‚。 + //ãれã¯ã™ã¹ã¦ã®ãƒ‡ãƒã‚¤ã‚¹ã«å¯¾ã—ã¦ä¸€æ„ã§ã‚ã‚‹ã“ã¨ãŒä¿è¨¼ã•ã‚Œã€æŽ¥ç¶šã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“//ユーザー アカウント。 + //Windows Phone 7: デãƒã‚¤ã‚¹ + ç¾åœ¨ã®ãƒ¦ãƒ¼ã‚¶ãƒ¼ã®ãƒãƒƒã‚·ãƒ¥ã‚’è¿”ã—ã¾ã™//ユーザーãŒå®šç¾©ã•れã¦ã„ãªã„å ´åˆ guid ãŒç”Ÿæˆã•れã€ã‚¢ãƒ—リãŒã‚¢ãƒ³ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã•れるã¾ã§ä¿æŒã•れã¾ã™//Tizen: デãƒã‚¤ã‚¹ã® IMEI ã‚’è¿”ã—ã¾ã™ (国際モãƒã‚¤ãƒ«æ©Ÿå™¨ã‚¢ã‚¤ãƒ‡ãƒ³ãƒ†ã‚£ãƒ†ã‚£ã¾ãŸã¯ IMEI ã¯ç•ªå·ã§ã™//ã™ã¹ã¦ã® GSM ãŠã‚ˆã³ UMTS ã®æºå¸¯é›»è©±ã«å›ºæœ‰ã§ã™ã€‚ + var deviceID = device.uuid; + + +### iOS ã®æ°—ã¾ãれ + +`uuid`IOS ã§ã€ãƒ‡ãƒã‚¤ã‚¹ã«å›ºæœ‰ã§ã¯ãªã„インストールã”ã¨ã€ã‚¢ãƒ—リケーションã”ã¨ã«ç•°ãªã‚Šã¾ã™ã€‚ 削除ã€ã‚¢ãƒ—リをå†ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã—ãŸå ´åˆã«å¤‰æ›´ã¨å¤šåˆ†ã¾ãŸã¨ãアップグレード iOS ã®, ã¾ãŸã¯ã‚‚アップグレードã™ã‚‹ã‚¢ãƒ—リ (iOS ã® 5.1 ã§æ˜Žã‚‰ã‹ã«ï¼‰ ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã”ã¨ã€‚ `uuid`ã¯ä¿¡é ¼æ€§ã®é«˜ã„値ã§ã¯ã‚りã¾ã›ã‚“。 + +### Windows Phone 7 㨠8 ç™– + +`uuid`ã®ãŸã‚ã« Windows Phone 7 ã«ã¯ã€æ¨©é™ãŒå¿…è¦ã§ã™ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft ã¯ã™ãã«ã“ã®ãƒ—ãƒãƒ‘ティを廃æ¢ã—ã¦å¯èƒ½æ€§ãŒã‚りã¾ã™ã€‚ 機能ãŒåˆ©ç”¨ã§ããªã„å ´åˆã€ã‚¢ãƒ—リケーションã¯ãƒ‡ãƒã‚¤ã‚¹ã¸ã®ã‚¢ãƒ—リケーションã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã®æŒç¶šæœŸé–“ã®ãŸã‚ã«ä¿æŒã•れã¦ã„る永続的㪠guid を生æˆã—ã¾ã™ã€‚ + +## device.version + +オペレーティング システムã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å–å¾—ã—ã¾ã™ã€‚ + + var string = device.version; + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* アンドãƒã‚¤ãƒ‰ 2.1 + +* ブラックベリー 10 +* ブラウザー +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +### ç°¡å˜ãªä¾‹ + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/ko/README.md new file mode 100644 index 00000000..a818aacb --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/ko/README.md @@ -0,0 +1,203 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +ì´ í”ŒëŸ¬ê·¸ì¸ ì •ì˜ ì „ì— `device` 개체, 디바ì´ìŠ¤ì˜ í•˜ë“œì›¨ì–´ ë° ì†Œí”„íŠ¸ì›¨ì–´ì— ì„¤ëª… 합니다. 개체는 ì „ì— ë²”ìœ„ì—서 ë¹„ë¡ ê·¸ê²ƒì€ í›„ê¹Œì§€ ì‚¬ìš©í• ìˆ˜ 있는 `deviceready` ì´ë²¤íЏ. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## 설치 + + cordova plugin add cordova-plugin-device + + +## ì†ì„± + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +코르ë„바는 장치ì—서 실행 ì¤‘ì¸ ë²„ì „ì„ ì–»ì„. + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * 브ë¼ìš°ì € + * Firefox ìš´ì˜ ì²´ì œ + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + +## device.model + +`device.model`소ìžì˜ ëª¨ë¸ ë˜ëŠ” ì œí’ˆì˜ ì´ë¦„ì„ ë°˜í™˜ 합니다. ê°’ 장치 ì œì¡°ì—…ì²´ì—서 ì„¤ì • ë˜ ê³ ë™ì¼ ì œí’ˆì˜ ë²„ì „ ê°„ì— ë‹¤ë¥¼ 수 있습니다. + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * 브ë¼ìš°ì € + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models 참조 / / var ëª¨ë¸ = device.model; + + +### 안 드 로ì´ë“œ 단ì + + * ì–´ë–¤ì€ ì¢…ì¢… 프로ë•ì…˜ 코드 ì´ë¦„ ëŒ€ì‹ [ì œí’ˆ ëª¨ë¸ ì´ë¦„](http://developer.android.com/reference/android/os/Build.html#MODEL), [ì œí’ˆ ì´ë¦„](http://developer.android.com/reference/android/os/Build.html#PRODUCT) ì„ ê°€ì ¸ì˜µë‹ˆë‹¤. 예를 들어 넥서스 하나 반환 합니다 `Passion` , ëª¨í† ë¡œë¼ Droid를 반환 합니다`voles`. + +### Tizen 특수 + + * 예를 들어, 공급 ì—…ì²´ì— ì˜í•´ í• ë‹¹ ëœ ë””ë°”ì´ìФ 모ë¸ì„ 반환 합니다.`TIZEN` + +### Windows Phone 7, 8 특수 + + * ì œì¡°ì—…ì²´ì—서 ì§€ì • 하는 장치 모ë¸ì„ 반환 합니다. 예를 들어 삼성 í¬ì»¤ìŠ¤ë¥¼ 반환 합니다.`SGH-i917`. + +## device.platform + +ìž¥ì¹˜ì˜ ìš´ì˜ ì²´ì œ ì´ë¦„ì„ ì–»ì„. + + var string = device.platform; + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * Browser4 + * Firefox ìš´ì˜ ì²´ì œ + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 단ì + +Windows Phone 7 장치 ë³´ê³ í”Œëž«í¼ìœ¼ë¡œ`WinCE`. + +### Windows Phone 8 단ì + +Windows Phone 8 장치 ë³´ê³ í”Œëž«í¼ìœ¼ë¡œ`Win32NT`. + +## device.uuid + +소ìžì˜ 보편ì 으로 ê³ ìœ ì‹ë³„ìž ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) 를 ì–»ì„합니다). + + var string = device.uuid; + + +### 설명 + +UUID ìƒì„± ë°©ë²•ì˜ ìžì„¸í•œ ë‚´ìš©ì€ ìž¥ì¹˜ ì œì¡°ì—…ì²´ì— ì˜í•´ ê²°ì • ë©ë‹ˆë‹¤ ë° ì†Œìžì˜ í”Œëž«í¼ ì´ë‚˜ 모ë¸. + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + / / 안 드 로ì´ë“œ: (문ìžì—´ë¡œ 다시!) ìž„ì˜ì˜ 64 비트 ì •ìˆ˜ë¥¼ 반환 합니다 / / ì •ìˆ˜ ìž¥ì¹˜ì˜ ì²« 번째 부팅ì—서 ìƒì„± / / / / ë¸”ëž™ë² ë¦¬: 디바ì´ìŠ¤ì˜ í•€ 번호를 반환 합니다 / / ì´ê²ƒì€ 9 ìžë¦¬ ê³ ìœ ì •ìˆ˜ (문ìžì—´ë¡œ 비ë¡!) / / / / ì•„ì´í°: (UIDevice í´ëž˜ìФ 설명서ì—서 ìŠ ì—ˆ) / / 문ìžì—´ 여러 하드웨어ì—서 ìƒì„± 하는 해시 ê°’ì„ ì‹ë³„ 하는 반환 합니다. + / ê·¸ê²ƒì€ ëª¨ë“ ìž¥ì¹˜ì— ëŒ€ 한 ê³ ìœ í•´ì•¼ 보장 ë˜ ê³ ë¬¶ì¼ ìˆ˜ 없습니다 / / / ì‚¬ìš©ìž ê³„ì •ì—. + / / Windows Phone 7: 장치 + 현재 사용ìžì˜ 해시를 반환 합니다 / / ì‚¬ìš©ìž ì •ì˜ ë˜ì§€ ì•Šì€ ê²½ìš° guid ìƒì„± ë˜ ê³ ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì œê±°í• ë•Œê¹Œì§€ ìœ ì§€ ë©ë‹ˆë‹¤ / / Tizen: 반환 장치 IMEI (êµì œ ëª¨ë°”ì¼ ê¸°ê¸° ì‹ë³„ ë˜ëŠ” IMEI 숫ìžìž…니다 / / ëª¨ë“ GSM와 UMTS 휴대 ì „í™” ê³ ìœ . + var deviceID = device.uuid; + + +### iOS 특질 + +`uuid`ios ìž¥ì¹˜ì— ê³ ìœ í•˜ì§€ 않습니다 하지만 ê° ì„¤ì¹˜ì— ëŒ€ 한 ì‘ìš© 프로그램 마다 다릅니다. ì‚ì œ 하 ê³ ë‹¤ì‹œ ì• í”Œ 리 ì¼€ì´ ì…˜ì„ ì„¤ì¹˜ 하는 경우 변경 가능 하 게 ë˜í•œ iOS를 ì—…ê·¸ë ˆì´ë“œ 하거나 때 ë²„ì „ (iOS 5.1ì—ì—서 명백한) 당 ì‘ìš© 프로그램 ì—…ê·¸ë ˆì´ë“œë„ 하 ê³ . `uuid`ì€ ì‹ ë¢°í• ìˆ˜ 있는 ê°’ì´ ì•„ë‹™ë‹ˆë‹¤. + +### Windows Phone 7, 8 특수 + +`uuid`Windows Phone 7 í•„ìš” 허가 `ID_CAP_IDENTITY_DEVICE` . Microsoft는 ê³§ì´ ì†ì„±ì„ 세ì›ë‹ˆë‹¤ ê°€ëŠ¥ì„±ì´ ê²ƒìž…ë‹ˆë‹¤. ê¸°ëŠ¥ì„ ì‚¬ìš©í• ìˆ˜ 없는 경우 ì‘ìš© 프로그램 ìž¥ì¹˜ì— ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ì„¤ì¹˜ 하는 ë™ì•ˆ ìœ ì§€ 하는 ì˜êµ¬ guid를 ìƒì„± 합니다. + +## device.version + +ìš´ì˜ ì²´ì œ ë²„ì „ì„ ì–»ì„. + + var string = device.version; + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 안 드 로ì´ë“œ 2.1 + + * ë¸”ëž™ë² ë¦¬ 10 + * 브ë¼ìš°ì € + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/ko/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/ko/index.md new file mode 100644 index 00000000..0fe38a7a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/ko/index.md @@ -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. +--> + +# cordova-plugin-device + +ì´ í”ŒëŸ¬ê·¸ì¸ ì •ì˜ ì „ì— `device` 개체, 디바ì´ìŠ¤ì˜ í•˜ë“œì›¨ì–´ ë° ì†Œí”„íŠ¸ì›¨ì–´ì— ì„¤ëª… 합니다. 개체는 ì „ì— ë²”ìœ„ì—서 ë¹„ë¡ ê·¸ê²ƒì€ í›„ê¹Œì§€ ì‚¬ìš©í• ìˆ˜ 있는 `deviceready` ì´ë²¤íЏ. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## 설치 + + cordova plugin add cordova-plugin-device + + +## ì†ì„± + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +코르ë„바는 장치ì—서 실행 ì¤‘ì¸ ë²„ì „ì„ ì–»ì„. + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* 브ë¼ìš°ì € +* Firefox ìš´ì˜ ì²´ì œ +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +## device.model + +`device.model`소ìžì˜ ëª¨ë¸ ë˜ëŠ” ì œí’ˆì˜ ì´ë¦„ì„ ë°˜í™˜ 합니다. ê°’ 장치 ì œì¡°ì—…ì²´ì—서 ì„¤ì • ë˜ ê³ ë™ì¼ ì œí’ˆì˜ ë²„ì „ ê°„ì— ë‹¤ë¥¼ 수 있습니다. + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* 브ë¼ìš°ì € +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models 참조 / / var ëª¨ë¸ = device.model; + + +### 안 드 로ì´ë“œ 단ì + +* ì–´ë–¤ì€ ì¢…ì¢… 프로ë•ì…˜ 코드 ì´ë¦„ ëŒ€ì‹ [ì œí’ˆ ëª¨ë¸ ì´ë¦„][1], [ì œí’ˆ ì´ë¦„][2] ì„ ê°€ì ¸ì˜µë‹ˆë‹¤. 예를 들어 넥서스 하나 반환 합니다 `Passion` , ëª¨í† ë¡œë¼ Droid를 반환 합니다`voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#MODEL + [2]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + +### Tizen 특수 + +* 예를 들어, 공급 ì—…ì²´ì— ì˜í•´ í• ë‹¹ ëœ ë””ë°”ì´ìФ 모ë¸ì„ 반환 합니다.`TIZEN` + +### Windows Phone 7, 8 특수 + +* ì œì¡°ì—…ì²´ì—서 ì§€ì • 하는 장치 모ë¸ì„ 반환 합니다. 예를 들어 삼성 í¬ì»¤ìŠ¤ë¥¼ 반환 합니다.`SGH-i917`. + +## device.platform + +ìž¥ì¹˜ì˜ ìš´ì˜ ì²´ì œ ì´ë¦„ì„ ì–»ì„. + + var string = device.platform; + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* Browser4 +* Firefox ìš´ì˜ ì²´ì œ +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 단ì + +Windows Phone 7 장치 ë³´ê³ í”Œëž«í¼ìœ¼ë¡œ`WinCE`. + +### Windows Phone 8 단ì + +Windows Phone 8 장치 ë³´ê³ í”Œëž«í¼ìœ¼ë¡œ`Win32NT`. + +## device.uuid + +소ìžì˜ 보편ì 으로 ê³ ìœ ì‹ë³„ìž ([UUID][3] 를 ì–»ì„합니다). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### 설명 + +UUID ìƒì„± ë°©ë²•ì˜ ìžì„¸í•œ ë‚´ìš©ì€ ìž¥ì¹˜ ì œì¡°ì—…ì²´ì— ì˜í•´ ê²°ì • ë©ë‹ˆë‹¤ ë° ì†Œìžì˜ í”Œëž«í¼ ì´ë‚˜ 모ë¸. + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + / / 안 드 로ì´ë“œ: (문ìžì—´ë¡œ 다시!) ìž„ì˜ì˜ 64 비트 ì •ìˆ˜ë¥¼ 반환 합니다 / / ì •ìˆ˜ ìž¥ì¹˜ì˜ ì²« 번째 부팅ì—서 ìƒì„± / / / / ë¸”ëž™ë² ë¦¬: 디바ì´ìŠ¤ì˜ í•€ 번호를 반환 합니다 / / ì´ê²ƒì€ 9 ìžë¦¬ ê³ ìœ ì •ìˆ˜ (문ìžì—´ë¡œ 비ë¡!) / / / / ì•„ì´í°: (UIDevice í´ëž˜ìФ 설명서ì—서 ìŠ ì—ˆ) / / 문ìžì—´ 여러 하드웨어ì—서 ìƒì„± 하는 해시 ê°’ì„ ì‹ë³„ 하는 반환 합니다. + / ê·¸ê²ƒì€ ëª¨ë“ ìž¥ì¹˜ì— ëŒ€ 한 ê³ ìœ í•´ì•¼ 보장 ë˜ ê³ ë¬¶ì¼ ìˆ˜ 없습니다 / / / ì‚¬ìš©ìž ê³„ì •ì—. + / / Windows Phone 7: 장치 + 현재 사용ìžì˜ 해시를 반환 합니다 / / ì‚¬ìš©ìž ì •ì˜ ë˜ì§€ ì•Šì€ ê²½ìš° guid ìƒì„± ë˜ ê³ ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì œê±°í• ë•Œê¹Œì§€ ìœ ì§€ ë©ë‹ˆë‹¤ / / Tizen: 반환 장치 IMEI (êµì œ ëª¨ë°”ì¼ ê¸°ê¸° ì‹ë³„ ë˜ëŠ” IMEI 숫ìžìž…니다 / / ëª¨ë“ GSM와 UMTS 휴대 ì „í™” ê³ ìœ . + var deviceID = device.uuid; + + +### iOS 특질 + +`uuid`ios ìž¥ì¹˜ì— ê³ ìœ í•˜ì§€ 않습니다 하지만 ê° ì„¤ì¹˜ì— ëŒ€ 한 ì‘ìš© 프로그램 마다 다릅니다. ì‚ì œ 하 ê³ ë‹¤ì‹œ ì• í”Œ 리 ì¼€ì´ ì…˜ì„ ì„¤ì¹˜ 하는 경우 변경 가능 하 게 ë˜í•œ iOS를 ì—…ê·¸ë ˆì´ë“œ 하거나 때 ë²„ì „ (iOS 5.1ì—ì—서 명백한) 당 ì‘ìš© 프로그램 ì—…ê·¸ë ˆì´ë“œë„ 하 ê³ . `uuid`ì€ ì‹ ë¢°í• ìˆ˜ 있는 ê°’ì´ ì•„ë‹™ë‹ˆë‹¤. + +### Windows Phone 7, 8 특수 + +`uuid`Windows Phone 7 í•„ìš” 허가 `ID_CAP_IDENTITY_DEVICE` . Microsoft는 ê³§ì´ ì†ì„±ì„ 세ì›ë‹ˆë‹¤ ê°€ëŠ¥ì„±ì´ ê²ƒìž…ë‹ˆë‹¤. ê¸°ëŠ¥ì„ ì‚¬ìš©í• ìˆ˜ 없는 경우 ì‘ìš© 프로그램 ìž¥ì¹˜ì— ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ì„¤ì¹˜ 하는 ë™ì•ˆ ìœ ì§€ 하는 ì˜êµ¬ guid를 ìƒì„± 합니다. + +## device.version + +ìš´ì˜ ì²´ì œ ë²„ì „ì„ ì–»ì„. + + var string = device.version; + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 안 드 로ì´ë“œ 2.1 + +* ë¸”ëž™ë² ë¦¬ 10 +* 브ë¼ìš°ì € +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +### ë¹ ë¥¸ ì˜ˆì œ + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/pl/README.md new file mode 100644 index 00000000..c38832df --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/pl/README.md @@ -0,0 +1,214 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +Ten plugin okreÅ›la globalne `device` obiekt, który opisuje urzÄ…dzenia sprzÄ™towe i programowe. Mimo, że obiekt jest w globalnym zasiÄ™gu, nie jest dostÄ™pne dopiero po `deviceready` zdarzenie. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Instalacja + + cordova plugin add cordova-plugin-device + + +## WÅ‚aÅ›ciwoÅ›ci + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +Pobierz wersjÄ™ Cordova dziaÅ‚a na urzÄ…dzeniu. + +### ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * PrzeglÄ…darka + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + +## device.model + +`device.model`Zwraca nazwÄ™ modelu lub produktu. Wartość jest zestaw przez producenta urzÄ…dzenia i mogÄ… siÄ™ różnić miÄ™dzy wersjami tego samego produktu. + +### ObsÅ‚ugiwane platformy + + * Android + * BlackBerry 10 + * PrzeglÄ…darka + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + +### Szybki przykÅ‚ad + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Zobacz http://theiphonewiki.com/wiki/index.php?title=Models / / modelu var = device.model; + + +### Dziwactwa Androida + + * Pobiera [nazwÄ™ produktu](http://developer.android.com/reference/android/os/Build.html#PRODUCT) zamiast [nazwy modelu](http://developer.android.com/reference/android/os/Build.html#MODEL), który czÄ™sto jest nazwÄ… kod produkcji. Na przykÅ‚ad, Nexus One zwraca `Passion` , i zwraca Motorola Droid`voles`. + +### Dziwactwa Tizen + + * Zwraca modelu urzÄ…dzenia przypisane przez dostawcÄ™, na przykÅ‚ad,`TIZEN` + +### Windows Phone 7 i 8 dziwactwa + + * Zwraca modelu urzÄ…dzenia, okreÅ›lonej przez producenta. Na przykÅ‚ad Samsung ostroÅ›ci zwraca`SGH-i917`. + +## device.platform + +Uzyskać nazwÄ™ systemu operacyjnego urzÄ…dzenia. + + var string = device.platform; + + +### ObsÅ‚ugiwane platformy + + * Android + * BlackBerry 10 + * Browser4 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + +### Szybki przykÅ‚ad + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Dziwactwa Windows Phone 7 + +UrzÄ…dzenia Windows Phone 7 raport platformy jako`WinCE`. + +### Windows Phone 8 dziwactwa + +UrzÄ…dzenia Windows Phone 8 raport platformy jako`Win32NT`. + +## device.uuid + +SiÄ™ urzÄ…dzenia uniwersalnie unikatowy identyfikator ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). + + var string = device.uuid; + + +### Opis + +Szczegóły jak UUID jest generowane sÄ… okreÅ›lane przez producenta urzÄ…dzenia i sÄ… specyficzne dla platformy lub modelu urzÄ…dzenia. + +### ObsÅ‚ugiwane platformy + + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + +### Szybki przykÅ‚ad + + // Android: Returns a random 64-bit integer (as a string, again!) + // The integer is generated on the device's first boot + // + // BlackBerry: Returns the PIN number of the device + // This is a nine-digit unique integer (as a string, though!) + // + // iPhone: (Paraphrased from the UIDevice Class documentation) + // Returns a string of hash values created from multiple hardware identifies. + // It is guaranteed to be unique for every device and can't be tied + // to the user account. + // Windows Phone 7 : Returns a hash of device+current user, + // if the user is not defined, a guid is generated and will persist until the app is uninstalled + // Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number + // unique to every GSM and UMTS mobile phone. + var deviceID = device.uuid; + + +### iOS dziwactwo + +`uuid`Na iOS nie jest przypisany do urzÄ…dzenia, ale różni siÄ™ dla każdej aplikacji, dla każdej instalacji. Zmienia siÄ™ jeÅ›li możesz usunąć i ponownie zainstalować aplikacjÄ™, a ewentualnie także po aktualizacji iOS czy nawet uaktualnienia aplikacji dla wersji (widoczny w iOS 5.1). `uuid`Jest nie wiarygodne wartoÅ›ci. + +### Windows Phone 7 i 8 dziwactwa + +`uuid`Dla Windows Phone 7 wymaga uprawnieÅ„ `ID_CAP_IDENTITY_DEVICE` . Microsoft bÄ™dzie prawdopodobnie potÄ™piać ten wkrótce. JeÅ›li funkcja nie jest dostÄ™pna, aplikacja generuje trwaÅ‚e identyfikator guid, który jest utrzymywany przez czas trwania instalacji aplikacji na urzÄ…dzeniu. + +## device.version + +Pobierz wersjÄ™ systemu operacyjnego. + + var string = device.version; + + +### ObsÅ‚ugiwane platformy + + * Android 2.1 + + * BlackBerry 10 + * PrzeglÄ…darka + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + +### Szybki przykÅ‚ad + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/pl/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/pl/index.md new file mode 100644 index 00000000..acc8f9c8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/pl/index.md @@ -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. +--> + +# cordova-plugin-device + +Ten plugin okreÅ›la globalne `device` obiekt, który opisuje urzÄ…dzenia sprzÄ™towe i programowe. Mimo, że obiekt jest w globalnym zasiÄ™gu, nie jest dostÄ™pne dopiero po `deviceready` zdarzenie. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## Instalacja + + cordova plugin add cordova-plugin-device + + +## WÅ‚aÅ›ciwoÅ›ci + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +Pobierz wersjÄ™ Cordova dziaÅ‚a na urzÄ…dzeniu. + +### ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* PrzeglÄ…darka +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +## device.model + +`device.model`Zwraca nazwÄ™ modelu lub produktu. Wartość jest zestaw przez producenta urzÄ…dzenia i mogÄ… siÄ™ różnić miÄ™dzy wersjami tego samego produktu. + +### ObsÅ‚ugiwane platformy + +* Android +* BlackBerry 10 +* PrzeglÄ…darka +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +### Szybki przykÅ‚ad + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Zobacz http://theiphonewiki.com/wiki/index.php?title=Models / / modelu var = device.model; + + +### Dziwactwa Androida + +* Pobiera [nazwÄ™ produktu][1] zamiast [nazwy modelu][2], który czÄ™sto jest nazwÄ… kod produkcji. Na przykÅ‚ad, Nexus One zwraca `Passion` , i zwraca Motorola Droid`voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### Dziwactwa Tizen + +* Zwraca modelu urzÄ…dzenia przypisane przez dostawcÄ™, na przykÅ‚ad,`TIZEN` + +### Windows Phone 7 i 8 dziwactwa + +* Zwraca modelu urzÄ…dzenia, okreÅ›lonej przez producenta. Na przykÅ‚ad Samsung ostroÅ›ci zwraca`SGH-i917`. + +## device.platform + +Uzyskać nazwÄ™ systemu operacyjnego urzÄ…dzenia. + + var string = device.platform; + + +### ObsÅ‚ugiwane platformy + +* Android +* BlackBerry 10 +* Browser4 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +### Szybki przykÅ‚ad + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Dziwactwa Windows Phone 7 + +UrzÄ…dzenia Windows Phone 7 raport platformy jako`WinCE`. + +### Windows Phone 8 dziwactwa + +UrzÄ…dzenia Windows Phone 8 raport platformy jako`Win32NT`. + +## device.uuid + +SiÄ™ urzÄ…dzenia uniwersalnie unikatowy identyfikator ([UUID][3]). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### Opis + +Szczegóły jak UUID jest generowane sÄ… okreÅ›lane przez producenta urzÄ…dzenia i sÄ… specyficzne dla platformy lub modelu urzÄ…dzenia. + +### ObsÅ‚ugiwane platformy + +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +### Szybki przykÅ‚ad + + / / Android: zwraca losowe 64-bitowa liczba caÅ‚kowita (jako ciÄ…g, znowu!) / / liczba caÅ‚kowita jest generowany na pierwszego uruchomienia urzÄ…dzenia / / / / BlackBerry: zwraca numer PIN urzÄ…dzenia / / to jest unikatowÄ… liczbÄ… caÅ‚kowitÄ… dziewiÄ™ciu cyfr (jako ciÄ…g, choć!) / / / / iPhone: (zacytowana w dokumentacji klasy UIDevice) / / zwraca ciÄ…g wartoÅ›ci mieszania utworzone z wielu sprzÄ™tu identyfikuje. + Zapewniona jest unikatowy dla każdego urzÄ…dzenia i nie może być zwiÄ…zane z / do konta użytkownika. + / / Windows Phone 7: zwraca wartość mieszania urzÄ…dzenia + bieżący użytkownik, / / jeÅ›li nie zdefiniowane przez użytkownika, identyfikator guid jest generowany i bÄ™dzie trwać do czasu odinstalowania aplikacji / / Tizen: zwraca urzÄ…dzenia IMEI (International Mobile Equipment Identity lub IMEI jest liczbÄ… / / unikatowe dla każdego telefonu komórkowego GSM i UMTS. + var deviceID = device.uuid; + + +### iOS dziwactwo + +`uuid`Na iOS nie jest przypisany do urzÄ…dzenia, ale różni siÄ™ dla każdej aplikacji, dla każdej instalacji. Zmienia siÄ™ jeÅ›li możesz usunąć i ponownie zainstalować aplikacjÄ™, a ewentualnie także po aktualizacji iOS czy nawet uaktualnienia aplikacji dla wersji (widoczny w iOS 5.1). `uuid`Jest nie wiarygodne wartoÅ›ci. + +### Windows Phone 7 i 8 dziwactwa + +`uuid`Dla Windows Phone 7 wymaga uprawnieÅ„ `ID_CAP_IDENTITY_DEVICE` . Microsoft bÄ™dzie prawdopodobnie potÄ™piać ten wkrótce. JeÅ›li funkcja nie jest dostÄ™pna, aplikacja generuje trwaÅ‚e identyfikator guid, który jest utrzymywany przez czas trwania instalacji aplikacji na urzÄ…dzeniu. + +## device.version + +Pobierz wersjÄ™ systemu operacyjnego. + + var string = device.version; + + +### ObsÅ‚ugiwane platformy + +* Android 2.1 + +* BlackBerry 10 +* PrzeglÄ…darka +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +### Szybki przykÅ‚ad + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/ru/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/ru/index.md new file mode 100644 index 00000000..263b1cd9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/ru/index.md @@ -0,0 +1,219 @@ +<!--- + 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-plugin-device + +Ðтот плагин определÑет глобальный объект `device`, который опиÑывает оборудование и программное обеÑпечение уÑтройÑтва. ÐеÑÐ¼Ð¾Ñ‚Ñ€Ñ Ð½Ð° то что объект в глобальной облаÑти видимоÑти, он не доÑтупен до того момента пока не произойдет Ñобытие `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## УÑтановка + + cordova plugin add cordova-plugin-device + + +## Параметры + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +Возвращает верÑию Cordova, работающую на уÑтройÑтве. + +### Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Обозреватель +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +## device.model + +СвойÑтво `device.model` возвращает Ð¸Ð¼Ñ ÑƒÑтройÑтва модели или продукта. Значение уÑтанавливаетÑÑ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÐµÐ¼ уÑтройÑтва и могут отличатьÑÑ Ð² разных верÑиÑÑ… одного и того же продукта. + +### Поддерживаемые платформы + +* Android +* BlackBerry 10 +* Обозреватель +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### Краткий пример + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models + // + var model = device.model; + + +### ОÑобенноÑти Android + +* Возвращает [Ð¸Ð¼Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð°][1] , а не [Ð¸Ð¼Ñ Ð¼Ð¾Ð´ÐµÐ»Ð¸][2], которое чаÑто ÑвлÑетÑÑ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ñтвенным кодом. Ðапример, Nexus One из них возвращает `Passion` , и Motorola Droid возвращает `voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### ОÑобенноÑти Tizen + +* Возвращает модель уÑтройÑтва, назначенного вендором, например,`TIZEN` + +### ОÑобенноÑти Windows Phone 7 и 8 + +* Возвращает модель уÑтройÑтва, указанной заводом-изготовителем. Ðапример Samsung Focus возвращает `SGH-i917`. + +## device.platform + +Получите Ð¸Ð¼Ñ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð¾Ð¹ ÑиÑтемы уÑтройÑтва. + + var string = device.platform; + + +### Поддерживаемые платформы + +* Android +* BlackBerry 10 +* Браузером4 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### Краткий пример + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### ОÑобенноÑти Windows Phone 7 + +Windows Phone 7 уÑтройÑтва Ñообщают платформу как `WinCE`. + +### ОÑобенноÑти Windows Phone 8 + +УÑтройÑтва Windows Phone 8 Ñообщают платформу как `Win32NT`. + +## device.uuid + +Возвращает универÑальный уникального идентификатора ([UUID][3] уÑтройÑтва). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### ОпиÑание + +ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð°Ñ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ том как UUID генерируетÑÑ, определÑÑŽÑ‚ÑÑ Ð¸Ð·Ð³Ð¾Ñ‚Ð¾Ð²Ð¸Ñ‚ÐµÐ»ÐµÐ¼ уÑтройÑтва и ÑвлÑÑŽÑ‚ÑÑ ÑпецифичеÑкими Ð´Ð»Ñ Ð¿Ð»Ð°Ñ‚Ñ„Ð¾Ñ€Ð¼Ñ‹ или модели уÑтройÑтва. + +### Поддерживаемые платформы + +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### Краткий пример + + // Android: Возвращает Ñлучайное 64-разрÑдное целое чиÑло (в виде Ñтроки, опÑть!) + // целое чиÑло генерируетÑÑ Ð¿Ñ€Ð¸ первой загрузке уÑтройÑтва + // + // BlackBerry: Возвращает номер PIN уÑтройÑтва + // Ñто 9 значный уникальный целочиÑленный (как Ñтрока, хотÑ!) + // + // iPhone: (Перефразировано из документации клаÑÑа UIDevice) + // возвращает Ñтроку Ñ…Ñш-значениÑ, Ñозданные из неÑкольких аппаратных определÑет. + // Ðто значение гарантированно ÑвлÑетÑÑ ÑƒÐ½Ð¸ÐºÐ°Ð»ÑŒÐ½Ñ‹Ð¼ Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ уÑтройÑтва и не может быть привÑзано + // к учетной запиÑи пользователÑ. + // Windows Phone 7: Возвращает Ñ…Ñш уÑтройÑтво + текущего пользователÑ, + // еÑли пользователь не определен, формируетÑÑ guid который и будет ÑохранÑтьÑÑ Ð´Ð¾ тех пор, пока приложение не удалитьÑÑ + // Tizen: возвращает IMEI уÑтройÑтва (Международный идентификатор мобильного Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¸Ð»Ð¸ IMEI Ñто чиÑло + // уникальное Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ мобильного телефона GSM и UMTS. + var deviceID = device.uuid; + + +### ОÑобенноÑти iOS + +Ðа iOS `uuid` не ÑвлÑетÑÑ ÑƒÐ½Ð¸ÐºÐ°Ð»ÑŒÐ½Ñ‹Ð¼ Ð´Ð»Ñ ÑƒÑтройÑтва, но варьируетÑÑ Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ приложениÑ, и Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð¹ уÑтановки. Значение менÑетÑÑ, еÑли удалить и повторно уÑтановить приложение, и возможно также когда вы обновите iOS, или даже обновить приложение до Ñледующей верÑии (очевидно в iOS 5.1). Значение `uuid` не ÑвлÑетÑÑ Ð½Ð°Ð´ÐµÐ¶Ð½Ñ‹Ð¼. + +### ОÑобенноÑти Windows Phone 7 и 8 + +Ð”Ð»Ñ Windows Phone 7 `uuid` требует Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð¸Ñ `ID_CAP_IDENTITY_DEVICE` . Microsoft Ñкорее вÑего Ñкоро Ñделает Ñто ÑвойÑтво уÑтаревшим. ЕÑли возможноÑть недоÑтупна, приложение Ñоздает поÑтоÑнные guid, который ÑохранÑетÑÑ Ð½Ð° вÑе Ð²Ñ€ÐµÐ¼Ñ ÑƒÑтановки Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð½Ð° уÑтройÑтве. + +## device.version + +Возвращает верÑию операционной ÑиÑтемы. + + var string = device.version; + + +### Поддерживаемые платформы + +* Android 2.1 + +* BlackBerry 10 +* Обозреватель +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### Краткий пример + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-device/doc/zh/README.md new file mode 100644 index 00000000..9a18a55e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/zh/README.md @@ -0,0 +1,203 @@ +<!-- +# license: 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-plugin-device + +[](https://travis-ci.org/apache/cordova-plugin-device) + +這個外掛程å¼å®šç¾©å…¨çƒ `device` 物件,æè¿°è©²è¨å‚™çš„硬體和軟體。 雖然物件是在全çƒç¯„åœå…§ï¼Œä½†ä¸æ˜¯å¯ç”¨ï¼Œç›´åˆ°å¾Œ `deviceready` 事件。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-device + + +## 屬性 + + * device.cordova + * device.model + * device.platform + * device.uuid + * device.version + +## device.cordova + +ç²å–科爾多瓦在è¨å‚™ä¸Šé‹è¡Œçš„版本。 + +### 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * ç€è¦½å™¨ + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + +## device.model + +`device.model`返回è¨å‚™çš„æ¨¡åž‹æˆ–產å“çš„å稱。值由è¨å‚™è£½é€ 商è¨ç½®å’ŒåŒä¸€ç”¢å“çš„ä¸åŒç‰ˆæœ¬å¯èƒ½ä¸åŒã€‚ + +### 支æ´çš„平臺 + + * Android 系統 + * 黑莓 10 + * ç€è¦½å™¨ + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + +### 快速的示例 + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. è«‹åƒé–± HTTP://theiphonewiki.com/wiki/index.php?title=Models / / var 模型 = device.model ï¼› + + +### Android 的怪癖 + + * ç²å–[產å“å稱](http://developer.android.com/reference/android/os/Build.html#PRODUCT)è€Œä¸æ˜¯[產å“型號å稱](http://developer.android.com/reference/android/os/Build.html#MODEL),這往往是生產代碼å稱。 例如,Nexus One 返回 `Passion` ,和摩托羅拉 Droid 返回`voles`. + +### Tizen 怪癖 + + * 例如,返回與供應商指派的è¨å‚™æ¨¡åž‹`TIZEN` + +### Windows Phone 7 å’Œ 8 怪癖 + + * è¿”å›žç”±è£½é€ å•†æŒ‡å®šçš„è¨å‚™æ¨¡åž‹ã€‚例如,三星焦點返回`SGH-i917`. + +## device.platform + +ç²å–è¨å‚™çš„作æ¥ç³»çµ±å稱。 + + var string = device.platform; + + +### 支æ´çš„平臺 + + * Android 系統 + * 黑莓 10 + * Browser4 + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + +### 快速的示例 + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 的怪癖 + +Windows Phone 7 è¨å‚™å ±å‘Šä½œç‚ºå¹³è‡º`WinCE`. + +### Windows Phone 8 怪癖 + +Windows Phone 8 è¨å‚™å ±å‘Šä½œç‚ºå¹³è‡º`Win32NT`. + +## device.uuid + +ç²å–è¨å‚™çš„通用唯一è˜åˆ¥ç¢¼ ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)). + + var string = device.uuid; + + +### 說明 + +如何生æˆä¸€å€‹ UUID 的細節由è¨å‚™è£½é€ 商和特定于è¨å‚™çš„平臺或模型。 + +### 支æ´çš„平臺 + + * Android 系統 + * 黑莓 10 + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + +### 快速的示例 + + / / Android: 一個隨機的 64 使•´æ•¸ (作為å—ä¸²è¿”å›žï¼Œå†æ¬¡!) / / 上è¨å‚™çš„第一次啟動生æˆçš„æ•´æ•¸ / / / / 黑莓手機: 返回è¨å‚™çš„ PIN 號碼 / / 這是ä¹å€‹æ•¸å—的唯一整數 (作為å—串,雖然!) / / / / iPhone: (從 UIDevice 類文檔解釋) / / 返回一個å—串的雜湊值創建的多個硬體標è˜ã€‚ + / / 它ä¿è‰æ˜¯å”¯ä¸€çš„æ¯å€‹è¨å‚™ä¸¦ä¸èƒ½ç¶ / / 到使用者帳戶。 + / / Windows Phone 7: 返回的雜湊代碼的è¨å‚™ + ç•¶å‰ä½¿ç”¨è€…,/ / 如果未定義使用者,則一個 guid 生æˆçš„並且將會ä¿ç•™ç›´åˆ°å¸è¼‰è©²æ‡‰ç”¨ç¨‹å¼ / / Tizen: 返回è¨å‚™ IMEI (國際行動è£ç½®èº«ä»½æˆ– IMEI æ˜¯ä¸€å€‹æ•¸ä½ / / ç¨æœ‰çš„æ¯ä¸€å€‹ UMTS å’Œ GSM 行動電話。 + var deviceID = device.uuid; + + +### iOS 怪癖 + +`uuid`在 iOS 䏿˜¯å”¯ä¸€çš„一種è£ç½®ï¼Œä½†å°æ–¼æ¯å€‹æ‡‰ç”¨ç¨‹å¼ï¼Œç‚ºæ¯å€‹å®‰è£è€Œç•°ã€‚ å¦‚æžœæ‚¨åˆªé™¤ä¸¦é‡æ–°å®‰è£è©²æ‡‰ç”¨ç¨‹å¼ï¼Œå®ƒæ›´æ”¹å’Œå¯èƒ½é‚„ç•¶ä½ å‡ç´š iOS,或甚至å‡ç´šæ¯å€‹ç‰ˆæœ¬ (iOS 5.1 ä¸å˜åœ¨æ˜Žé¡¯çš„) 的應用程å¼ã€‚ `uuid`䏿˜¯ä¸€å€‹å¯é 的值。 + +### Windows Phone 7 å’Œ 8 怪癖 + +`uuid`為 Windows Phone 7 é ˆç¶“è¨±å¯ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft å¯èƒ½æœƒå¾ˆå¿«æ£„用æ¤å±¬æ€§ã€‚ 如果沒有å¯ç”¨çš„能力,應用程å¼å°‡ç”Ÿæˆè¨å‚™ä¸Šæ‡‰ç”¨ç¨‹å¼çš„安è£éŽç¨‹ä¸ä¿æŒæŒçºŒçš„ guid。 + +## device.version + +ç²å–作æ¥ç³»çµ±ç‰ˆæœ¬ã€‚ + + var string = device.version; + + +### 支æ´çš„平臺 + + * Android 2.1 + + * 黑莓 10 + * ç€è¦½å™¨ + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + +### 快速的示例 + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version;
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-device/doc/zh/index.md b/StoneIsland/plugins/cordova-plugin-device/doc/zh/index.md new file mode 100644 index 00000000..5626d696 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/doc/zh/index.md @@ -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. +--> + +# cordova-plugin-device + +這個外掛程å¼å®šç¾©å…¨çƒ `device` 物件,æè¿°è©²è¨å‚™çš„硬體和軟體。 雖然物件是在全çƒç¯„åœå…§ï¼Œä½†ä¸æ˜¯å¯ç”¨ï¼Œç›´åˆ°å¾Œ `deviceready` 事件。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(device.cordova); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-device + + +## 屬性 + +* device.cordova +* device.model +* device.platform +* device.uuid +* device.version + +## device.cordova + +ç²å–科爾多瓦在è¨å‚™ä¸Šé‹è¡Œçš„版本。 + +### 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* ç€è¦½å™¨ +* ç«ç‹ç€è¦½å™¨çš„作æ¥ç³»çµ± +* iOS +* æ³° +* Windows Phone 7 å’Œ 8 +* Windows 8 + +## device.model + +`device.model`返回è¨å‚™çš„æ¨¡åž‹æˆ–產å“çš„å稱。值由è¨å‚™è£½é€ 商è¨ç½®å’ŒåŒä¸€ç”¢å“çš„ä¸åŒç‰ˆæœ¬å¯èƒ½ä¸åŒã€‚ + +### 支æ´çš„平臺 + +* Android 系統 +* 黑莓 10 +* ç€è¦½å™¨ +* iOS +* æ³° +* Windows Phone 7 å’Œ 8 +* Windows 8 + +### 快速的示例 + + // Android: Nexus One returns "Passion" (Nexus One code name) + // Motorola Droid returns "voles" + // BlackBerry: Torch 9800 returns "9800" + // Browser: Google Chrome returns "Chrome" + // Safari returns "Safari" + // iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. è«‹åƒé–± HTTP://theiphonewiki.com/wiki/index.php?title=Models / / var 模型 = device.model ï¼› + + +### Android 的怪癖 + +* ç²å–[產å“å稱][1]è€Œä¸æ˜¯[產å“型號å稱][2],這往往是生產代碼å稱。 例如,Nexus One 返回 `Passion` ,和摩托羅拉 Droid 返回`voles`. + + [1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT + [2]: http://developer.android.com/reference/android/os/Build.html#MODEL + +### Tizen 怪癖 + +* 例如,返回與供應商指派的è¨å‚™æ¨¡åž‹`TIZEN` + +### Windows Phone 7 å’Œ 8 怪癖 + +* è¿”å›žç”±è£½é€ å•†æŒ‡å®šçš„è¨å‚™æ¨¡åž‹ã€‚例如,三星焦點返回`SGH-i917`. + +## device.platform + +ç²å–è¨å‚™çš„作æ¥ç³»çµ±å稱。 + + var string = device.platform; + + +### 支æ´çš„平臺 + +* Android 系統 +* 黑莓 10 +* Browser4 +* ç«ç‹ç€è¦½å™¨çš„作æ¥ç³»çµ± +* iOS +* æ³° +* Windows Phone 7 å’Œ 8 +* Windows 8 + +### 快速的示例 + + // Depending on the device, a few examples are: + // - "Android" + // - "BlackBerry 10" + // - Browser: returns "MacIntel" on Mac + // returns "Win32" on Windows + // - "iOS" + // - "WinCE" + // - "Tizen" + var devicePlatform = device.platform; + + +### Windows Phone 7 的怪癖 + +Windows Phone 7 è¨å‚™å ±å‘Šä½œç‚ºå¹³è‡º`WinCE`. + +### Windows Phone 8 怪癖 + +Windows Phone 8 è¨å‚™å ±å‘Šä½œç‚ºå¹³è‡º`Win32NT`. + +## device.uuid + +ç²å–è¨å‚™çš„通用唯一è˜åˆ¥ç¢¼ ([UUID][3]). + + [3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier + + var string = device.uuid; + + +### 說明 + +如何生æˆä¸€å€‹ UUID 的細節由è¨å‚™è£½é€ 商和特定于è¨å‚™çš„平臺或模型。 + +### 支æ´çš„平臺 + +* Android 系統 +* 黑莓 10 +* iOS +* Tizen +* Windows Phone 7 å’Œ 8 +* Windows 8 + +### 快速的示例 + + / / Android: 一個隨機的 64 使•´æ•¸ (作為å—ä¸²è¿”å›žï¼Œå†æ¬¡!) / / 上è¨å‚™çš„第一次啟動生æˆçš„æ•´æ•¸ / / / / 黑莓手機: 返回è¨å‚™çš„ PIN 號碼 / / 這是ä¹å€‹æ•¸å—的唯一整數 (作為å—串,雖然!) / / / / iPhone: (從 UIDevice 類文檔解釋) / / 返回一個å—串的雜湊值創建的多個硬體標è˜ã€‚ + / / 它ä¿è‰æ˜¯å”¯ä¸€çš„æ¯å€‹è¨å‚™ä¸¦ä¸èƒ½ç¶ / / 到使用者帳戶。 + / / Windows Phone 7: 返回的雜湊代碼的è¨å‚™ + ç•¶å‰ä½¿ç”¨è€…,/ / 如果未定義使用者,則一個 guid 生æˆçš„並且將會ä¿ç•™ç›´åˆ°å¸è¼‰è©²æ‡‰ç”¨ç¨‹å¼ / / Tizen: 返回è¨å‚™ IMEI (國際行動è£ç½®èº«ä»½æˆ– IMEI æ˜¯ä¸€å€‹æ•¸ä½ / / ç¨æœ‰çš„æ¯ä¸€å€‹ UMTS å’Œ GSM 行動電話。 + var deviceID = device.uuid; + + +### iOS 怪癖 + +`uuid`在 iOS 䏿˜¯å”¯ä¸€çš„一種è£ç½®ï¼Œä½†å°æ–¼æ¯å€‹æ‡‰ç”¨ç¨‹å¼ï¼Œç‚ºæ¯å€‹å®‰è£è€Œç•°ã€‚ å¦‚æžœæ‚¨åˆªé™¤ä¸¦é‡æ–°å®‰è£è©²æ‡‰ç”¨ç¨‹å¼ï¼Œå®ƒæ›´æ”¹å’Œå¯èƒ½é‚„ç•¶ä½ å‡ç´š iOS,或甚至å‡ç´šæ¯å€‹ç‰ˆæœ¬ (iOS 5.1 ä¸å˜åœ¨æ˜Žé¡¯çš„) 的應用程å¼ã€‚ `uuid`䏿˜¯ä¸€å€‹å¯é 的值。 + +### Windows Phone 7 å’Œ 8 怪癖 + +`uuid`為 Windows Phone 7 é ˆç¶“è¨±å¯ `ID_CAP_IDENTITY_DEVICE` 。 Microsoft å¯èƒ½æœƒå¾ˆå¿«æ£„用æ¤å±¬æ€§ã€‚ 如果沒有å¯ç”¨çš„能力,應用程å¼å°‡ç”Ÿæˆè¨å‚™ä¸Šæ‡‰ç”¨ç¨‹å¼çš„安è£éŽç¨‹ä¸ä¿æŒæŒçºŒçš„ guid。 + +## device.version + +ç²å–作æ¥ç³»çµ±ç‰ˆæœ¬ã€‚ + + var string = device.version; + + +### 支æ´çš„平臺 + +* Android 2.1 + +* 黑莓 10 +* ç€è¦½å™¨ +* iOS +* æ³° +* Windows Phone 7 å’Œ 8 +* Windows 8 + +### 快速的示例 + + // Android: Froyo OS would return "2.2" + // Eclair OS would return "2.1", "2.0.1", or "2.0" + // Version can also return update level "2.1-update1" + // + // BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600" + // + // Browser: Returns version number for the browser + // + // iPhone: iOS 3.2 returns "3.2" + // + // Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720 + // Tizen: returns "TIZEN_20120425_2" + var deviceVersion = device.version; diff --git a/StoneIsland/plugins/cordova-plugin-device/package.json b/StoneIsland/plugins/cordova-plugin-device/package.json new file mode 100644 index 00000000..388b81d5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/package.json @@ -0,0 +1,45 @@ +{ + "name": "cordova-plugin-device", + "version": "1.0.1", + "description": "Cordova Device Plugin", + "cordova": { + "id": "cordova-plugin-device", + "platforms": [ + "firefoxos", + "tizen", + "android", + "amazon-fireos", + "ubuntu", + "ios", + "blackberry10", + "wp7", + "wp8", + "windows8", + "windows", + "browser" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-device" + }, + "keywords": [ + "cordova", + "device", + "ecosystem:cordova", + "cordova-firefoxos", + "cordova-tizen", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-blackberry10", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows", + "cordova-browser" + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-device/plugin.xml b/StoneIsland/plugins/cordova-plugin-device/plugin.xml new file mode 100644 index 00000000..172cff23 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/plugin.xml @@ -0,0 +1,161 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + xmlns:rim="http://www.blackberry.com/ns/widgets" + xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-device" + version="1.0.1"> + <name>Device</name> + <description>Cordova Device Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,device</keywords> + <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git</repo> + <issue>https://issues.apache.org/jira/browse/CB/component/12320648</issue> + + <js-module src="www/device.js" name="device"> + <clobbers target="device" /> + </js-module> + + <!-- firefoxos --> + <platform name="firefoxos"> + <config-file target="config.xml" parent="/*"> + <feature name="Device"> + <param name="firefoxos-package" value="Device" /> + </feature> + </config-file> + + <js-module src="src/firefoxos/DeviceProxy.js" name="DeviceProxy"> + <runs /> + </js-module> + </platform> + + <!-- tizen --> + <platform name="tizen"> + <js-module src="src/tizen/DeviceProxy.js" name="DeviceProxy"> + <runs /> + </js-module> + </platform> + + <!-- android --> + <platform name="android"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="Device" > + <param name="android-package" value="org.apache.cordova.device.Device"/> + </feature> + </config-file> + + <source-file src="src/android/Device.java" target-dir="src/org/apache/cordova/device" /> + </platform> + + <!-- amazon-fireos --> + <platform name="amazon-fireos"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="Device" > + <param name="android-package" value="org.apache.cordova.device.Device"/> + </feature> + </config-file> + + <source-file src="src/android/Device.java" target-dir="src/org/apache/cordova/device" /> + </platform> + + <!-- ubuntu --> + <platform name="ubuntu"> + <header-file src="src/ubuntu/device.h" /> + <source-file src="src/ubuntu/device.cpp" /> + <js-module src="src/ubuntu/device.js" name="DeviceProxy"> + <merges target="device" /> + </js-module> + </platform> + + <!-- ios --> + <platform name="ios"> + <config-file target="config.xml" parent="/*"> + <feature name="Device"> + <param name="ios-package" value="CDVDevice"/> + </feature> + </config-file> + + <header-file src="src/ios/CDVDevice.h" /> + <source-file src="src/ios/CDVDevice.m" /> + </platform> + + <!-- blackberry10 --> + <platform name="blackberry10"> + <source-file src="src/blackberry10/index.js" target-dir="Device" /> + <config-file target="www/config.xml" parent="/widget"> + <feature name="Device" value="Device"/> + </config-file> + <config-file target="www/config.xml" parent="/widget/rim:permissions"> + <rim:permit>read_device_identifying_information</rim:permit> + </config-file> + </platform> + + <!-- wp7 --> + <platform name="wp7"> + <config-file target="config.xml" parent="/*"> + <feature name="Device"> + <param name="wp-package" value="Device"/> + </feature> + </config-file> + + <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> + <Capability Name="ID_CAP_IDENTITY_DEVICE" /> + </config-file> + + <source-file src="src/wp/Device.cs" /> + </platform> + + <!-- wp8 --> + <platform name="wp8"> + <config-file target="config.xml" parent="/*"> + <feature name="Device"> + <param name="wp-package" value="Device"/> + </feature> + </config-file> + + <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> + <Capability Name="ID_CAP_IDENTITY_DEVICE" /> + </config-file> + + <source-file src="src/wp/Device.cs" /> + </platform> + + <!-- windows --> + <platform name="windows"> + <js-module src="src/windows/DeviceProxy.js" name="DeviceProxy"> + <merges target="" /> + </js-module> + </platform> + + <!-- browser --> + <platform name="browser"> + <config-file target="config.xml" parent="/*"> + <feature name="Device"> + <param name="browser-package" value="Device" /> + </feature> + </config-file> + + <js-module src="src/browser/DeviceProxy.js" name="DeviceProxy"> + <runs /> + </js-module> + </platform> + +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-device/src/android/Device.java b/StoneIsland/plugins/cordova-plugin-device/src/android/Device.java new file mode 100644 index 00000000..5eded907 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/android/Device.java @@ -0,0 +1,161 @@ +/* + 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. +*/ +package org.apache.cordova.device; + +import java.util.TimeZone; + +import org.apache.cordova.CordovaWebView; +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaInterface; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.provider.Settings; + +public class Device extends CordovaPlugin { + public static final String TAG = "Device"; + + public static String platform; // Device OS + public static String uuid; // Device UUID + + private static final String ANDROID_PLATFORM = "Android"; + private static final String AMAZON_PLATFORM = "amazon-fireos"; + private static final String AMAZON_DEVICE = "Amazon"; + + /** + * Constructor. + */ + public Device() { + } + + /** + * Sets the context of the Command. This can then be used to do things like + * get file paths associated with the Activity. + * + * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. + */ + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + Device.uuid = getUuid(); + } + + /** + * Executes the request and returns PluginResult. + * + * @param action The action to execute. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback id used when calling back into JavaScript. + * @return True if the action was valid, false if not. + */ + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + if (action.equals("getDeviceInfo")) { + JSONObject r = new JSONObject(); + r.put("uuid", Device.uuid); + r.put("version", this.getOSVersion()); + r.put("platform", this.getPlatform()); + r.put("model", this.getModel()); + r.put("manufacturer", this.getManufacturer()); + callbackContext.success(r); + } + else { + return false; + } + return true; + } + + //-------------------------------------------------------------------------- + // LOCAL METHODS + //-------------------------------------------------------------------------- + + /** + * Get the OS name. + * + * @return + */ + public String getPlatform() { + String platform; + if (isAmazonDevice()) { + platform = AMAZON_PLATFORM; + } else { + platform = ANDROID_PLATFORM; + } + return platform; + } + + /** + * Get the device's Universally Unique Identifier (UUID). + * + * @return + */ + public String getUuid() { + String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); + return uuid; + } + + public String getModel() { + String model = android.os.Build.MODEL; + return model; + } + + public String getProductName() { + String productname = android.os.Build.PRODUCT; + return productname; + } + + public String getManufacturer() { + String manufacturer = android.os.Build.MANUFACTURER; + return manufacturer; + } + /** + * Get the OS version. + * + * @return + */ + public String getOSVersion() { + String osversion = android.os.Build.VERSION.RELEASE; + return osversion; + } + + public String getSDKVersion() { + @SuppressWarnings("deprecation") + String sdkversion = android.os.Build.VERSION.SDK; + return sdkversion; + } + + public String getTimeZoneID() { + TimeZone tz = TimeZone.getDefault(); + return (tz.getID()); + } + + /** + * Function to check if the device is manufactured by Amazon + * + * @return + */ + public boolean isAmazonDevice() { + if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) { + return true; + } + return false; + } + +} diff --git a/StoneIsland/plugins/cordova-plugin-device/src/blackberry10/index.js b/StoneIsland/plugins/cordova-plugin-device/src/blackberry10/index.js new file mode 100644 index 00000000..77f25a9e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/blackberry10/index.js @@ -0,0 +1,69 @@ +/* + * + * 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 getModelName () { + var modelName = window.qnx.webplatform.device.modelName; + //Pre 10.2 (meaning Z10 or Q10) + if (typeof modelName === "undefined") { + if (window.screen.height === 720 && window.screen.width === 720) { + if ( window.matchMedia("(-blackberry-display-technology: -blackberry-display-oled)").matches) { + modelName = "Q10"; + } else { + modelName = "Q5"; + } + } else if ((window.screen.height === 1280 && window.screen.width === 768) || + (window.screen.height === 768 && window.screen.width === 1280)) { + modelName = "Z10"; + } else { + modelName = window.qnx.webplatform.deviceName; + } + } + + return modelName; +} + +function getUUID () { + var uuid = ""; + try { + //Must surround by try catch because this will throw if the app is missing permissions + uuid = window.qnx.webplatform.device.devicePin; + } catch (e) { + //DO Nothing + } + return uuid; +} + +module.exports = { + getDeviceInfo: function (success, fail, args, env) { + var result = new PluginResult(args, env), + modelName = getModelName(), + uuid = getUUID(), + info = { + manufacturer: 'BlackBerry', + platform: "blackberry10", + version: window.qnx.webplatform.device.scmBundle, + model: modelName, + uuid: uuid + }; + + result.ok(info); + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-device/src/browser/DeviceProxy.js b/StoneIsland/plugins/cordova-plugin-device/src/browser/DeviceProxy.js new file mode 100644 index 00000000..fcaed20c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/browser/DeviceProxy.js @@ -0,0 +1,82 @@ +/* + * + * 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 browser = require('cordova/platform'); +var cordova = require('cordova'); + +function getPlatform() { + return "browser"; +} + +function getModel() { + return getBrowserInfo(true); +} + +function getVersion() { + return getBrowserInfo(false); +} + +function getBrowserInfo(getModel) { + var userAgent = navigator.userAgent; + var returnVal = ''; + + if ((offset = userAgent.indexOf('Chrome')) !== -1) { + returnVal = (getModel) ? 'Chrome' : userAgent.substring(offset + 7); + } else if ((offset = userAgent.indexOf('Safari')) !== -1) { + if (getModel) { + returnVal = 'Safari'; + } else { + returnVal = userAgent.substring(offset + 7); + + if ((offset = userAgent.indexOf('Version')) !== -1) { + returnVal = userAgent.substring(offset + 8); + } + } + } else if ((offset = userAgent.indexOf('Firefox')) !== -1) { + returnVal = (getModel) ? 'Firefox' : userAgent.substring(offset + 8); + } else if ((offset = userAgent.indexOf('MSIE')) !== -1) { + returnVal = (getModel) ? 'MSIE' : userAgent.substring(offset + 5); + } else if ((offset = userAgent.indexOf('Trident')) !== -1) { + returnVal = (getModel) ? 'MSIE' : '11'; + } + + if ((offset = returnVal.indexOf(';')) !== -1 || (offset = returnVal.indexOf(' ')) !== -1) { + returnVal = returnVal.substring(0, offset); + } + + return returnVal; +} + + +module.exports = { + getDeviceInfo: function (success, error) { + setTimeout(function () { + success({ + cordova: browser.cordovaVersion, + platform: getPlatform(), + model: getModel(), + version: getVersion(), + uuid: null + }); + }, 0); + } +}; + +require("cordova/exec/proxy").add("Device", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-device/src/firefoxos/DeviceProxy.js b/StoneIsland/plugins/cordova-plugin-device/src/firefoxos/DeviceProxy.js new file mode 100644 index 00000000..79f3a2b0 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/firefoxos/DeviceProxy.js @@ -0,0 +1,79 @@ +/* + * + * 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. + * + */ +//example UA String for Firefox OS +//Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0 +var firefoxos = require('cordova/platform'); +var cordova = require('cordova'); + +//UA parsing not recommended but currently this is the only way to get the Firefox OS version +//https://developer.mozilla.org/en-US/docs/Gecko_user_agent_string_reference + +//Should be replaced when better conversion to Firefox OS Version is available +function convertVersionNumber(ver) { + var hashVersion = { + '18.0': '1.0.1', + '18.1': '1.1', + '26.0': '1.2', + '28.0': '1.3', + '30.0': '1.4', + '32.0': '2.0' + }; + var rver = ver; + var sStr = ver.substring(0, 4); + if (hashVersion[sStr]) { + rver = hashVersion[sStr]; + } + return (rver); + +} +function getVersion() { + if (navigator.userAgent.match(/(mobile|tablet)/i)) { + var ffVersionArray = (navigator.userAgent.match(/Firefox\/([\d]+\.[\w]?\.?[\w]+)/)); + if (ffVersionArray.length === 2) { + return (convertVersionNumber(ffVersionArray[1])); + } + } + return (null); +} + +function getModel() { + var uaArray = navigator.userAgent.split(/\s*[;)(]\s*/); + if (navigator.userAgent.match(/(mobile|tablet)/i)) { + if (uaArray.length === 5) { + return (uaArray[2]); + } + } + return (null); +} +module.exports = { + getDeviceInfo: function (success, error) { + setTimeout(function () { + success({ + platform: 'firefoxos', + model: getModel(), + version: getVersion(), + uuid: null + }); + }, 0); + } +}; + +require("cordova/exec/proxy").add("Device", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-device/src/ios/CDVDevice.h b/StoneIsland/plugins/cordova-plugin-device/src/ios/CDVDevice.h new file mode 100644 index 00000000..a146d882 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/ios/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; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-device/src/ios/CDVDevice.m b/StoneIsland/plugins/cordova-plugin-device/src/ios/CDVDevice.m new file mode 100644 index 00000000..5a3f4708 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/ios/CDVDevice.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. + */ + +#include <sys/types.h> +#include <sys/sysctl.h> + +#import <Cordova/CDV.h> +#import "CDVDevice.h" + +@implementation UIDevice (ModelVersion) + +- (NSString*)modelVersion +{ + 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); + + return platform; +} + +@end + +@interface CDVDevice () {} +@end + +@implementation CDVDevice + +- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device +{ + NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; + static NSString* UUID_KEY = @"CDVUUID"; + + NSString* app_uuid = [userDefaults stringForKey:UUID_KEY]; + + if (app_uuid == nil) { + CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); + CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); + + app_uuid = [NSString stringWithString:(__bridge NSString*)uuidString]; + [userDefaults setObject:app_uuid forKey:UUID_KEY]; + [userDefaults synchronize]; + + CFRelease(uuidString); + CFRelease(uuidRef); + } + + return app_uuid; +} + +- (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]; + NSMutableDictionary* devProps = [NSMutableDictionary dictionaryWithCapacity:4]; + + [devProps setObject:@"Apple" forKey:@"manufacturer"]; + [devProps setObject:[device modelVersion] forKey:@"model"]; + [devProps setObject:@"iOS" forKey:@"platform"]; + [devProps setObject:[device systemVersion] forKey:@"version"]; + [devProps setObject:[self uniqueAppInstanceIdentifier:device] forKey:@"uuid"]; + [devProps setObject:[[self class] cordovaVersion] forKey:@"cordova"]; + + NSDictionary* devReturn = [NSDictionary dictionaryWithDictionary:devProps]; + return devReturn; +} + ++ (NSString*)cordovaVersion +{ + return CDV_VERSION; +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-device/src/tizen/DeviceProxy.js b/StoneIsland/plugins/cordova-plugin-device/src/tizen/DeviceProxy.js new file mode 100644 index 00000000..2afc3243 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/tizen/DeviceProxy.js @@ -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. + * +*/ + +var tizen = require('cordova/platform'); +var cordova = require('cordova'); + +module.exports = { + getDeviceInfo: function(success, error) { + setTimeout(function () { + success({ + cordova: tizen.cordovaVersion, + platform: 'tizen', + model: null, + version: null, + uuid: null + }); + }, 0); + } +}; + +require("cordova/tizen/commandProxy").add("Device", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.cpp b/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.cpp new file mode 100644 index 00000000..eb5a012d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.cpp @@ -0,0 +1,64 @@ +/* + * Copyright 2011 Wolfgang Koller - http://www.gofg.at/ + * + * Licensed 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 <QDeviceInfo> +#include <QtSystemInfo> + +#include"device.h" + +#define CORDOVA "3.0.0" + +Device::Device(Cordova *cordova) : CPlugin(cordova) { +} + +static QString getOSName() { +#ifdef Q_OS_SYMBIAN + QString platform = "Symbian"; +#endif +#ifdef Q_OS_WIN + QString platform = "Windows"; +#endif +#ifdef Q_OS_WINCE + QString platform = "Windows CE"; +#endif +#ifdef Q_OS_LINUX + QString platform = "Linux"; +#endif + return platform; +} + +void Device::getInfo(int scId, int ecId) { + Q_UNUSED(ecId) + + QDeviceInfo systemDeviceInfo; + QDeviceInfo systemInfo; + + QString platform = getOSName(); + + QString uuid = systemDeviceInfo.uniqueDeviceID(); + if (uuid.isEmpty()) { + QString deviceDescription = systemInfo.imei(0) + ";" + systemInfo.manufacturer() + ";" + systemInfo.model() + ";" + systemInfo.productName() + ";" + platform; + QString user = qgetenv("USER"); + if (user.isEmpty()) { + user = qgetenv("USERNAME"); + if (user.isEmpty()) + user = QDir::homePath(); + } + uuid = QString(QCryptographicHash::hash((deviceDescription + ";" + user).toUtf8(), QCryptographicHash::Md5).toHex()); + } + + this->cb(scId, systemDeviceInfo.model(), CORDOVA, platform, uuid, systemInfo.version(QDeviceInfo::Os)); +} diff --git a/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.h b/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.h new file mode 100644 index 00000000..91cb9377 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.h @@ -0,0 +1,47 @@ +/* + * Copyright 2011 Wolfgang Koller - http://www.gofg.at/ + * + * Licensed 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 DEVICE_H_FDSAFAS +#define DEVICE_H_FDSAFAS + +#include <QtCore> + +#include <cplugin.h> + +class Device: public CPlugin { + Q_OBJECT +public: + explicit Device(Cordova *cordova); + + virtual const QString fullName() override { + return Device::fullID(); + } + + virtual const QString shortName() override { + return "Device"; + } + + static const QString fullID() { + return "com.cordova.Device"; + } + +signals: + +public slots: + void getInfo(int scId, int ecId); +}; + +#endif diff --git a/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.js b/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.js new file mode 100644 index 00000000..3adb110b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/ubuntu/device.js @@ -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. + * +*/ + +var cordova = require('cordova'); +var exec = require('cordova/exec'); + +module.exports = { + getInfo:function(win,fail,args) { + Cordova.exec(function (model, cordova, platform, uuid, version) { + win({name: name, model: model, cordova: cordova, + platform: platform, uuid: uuid, version: version}); + }, null, "com.cordova.Device", "getInfo", []); + } +}; + +require("cordova/exec/proxy").add("Device", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-device/src/windows/DeviceProxy.js b/StoneIsland/plugins/cordova-plugin-device/src/windows/DeviceProxy.js new file mode 100644 index 00000000..69ed4446 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/windows/DeviceProxy.js @@ -0,0 +1,108 @@ +/* + * + * 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 ROOT_CONTAINER = "{00000000-0000-0000-FFFF-FFFFFFFFFFFF}"; +var DEVICE_CLASS_KEY = "{A45C254E-DF1C-4EFD-8020-67D146A850E0},10"; +var DEVICE_CLASS_KEY_NO_SEMICOLON = '{A45C254E-DF1C-4EFD-8020-67D146A850E0}10'; +var ROOT_CONTAINER_QUERY = "System.Devices.ContainerId:=\"" + ROOT_CONTAINER + "\""; +var HAL_DEVICE_CLASS = "4d36e966-e325-11ce-bfc1-08002be10318"; +var DEVICE_DRIVER_VERSION_KEY = "{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3"; +var MANU_KEY = "System.Devices.Manufacturer"; + +module.exports = { + + getDeviceInfo:function(win, fail, args) { + + // deviceId aka uuid, stored in Windows.Storage.ApplicationData.current.localSettings.values.deviceId + var deviceId; + var manufacturer = "unknown"; + + // get deviceId, or create and store one + var localSettings = Windows.Storage.ApplicationData.current.localSettings; + if (localSettings.values.deviceId) { + deviceId = localSettings.values.deviceId; + } + else { + // App-specific hardware id could be used as uuid, but it changes if the hardware changes... + try { + var ASHWID = Windows.System.Profile.HardwareIdentification.getPackageSpecificToken(null).id; + deviceId = Windows.Storage.Streams.DataReader.fromBuffer(ASHWID).readGuid(); + } catch (e) { + // Couldn't get the hardware UUID + deviceId = createUUID(); + } + //...so cache it per-install + localSettings.values.deviceId = deviceId; + } + + + var userAgent = window.clientInformation.userAgent; + // this will report "windows" in windows8.1 and windows phone 8.1 apps + // and "windows8" in windows 8.0 apps similar to cordova.js + // See https://github.com/apache/cordova-js/blob/master/src/windows/platform.js#L25 + var devicePlatform = userAgent.indexOf("MSAppHost/1.0") == -1 ? "windows" : "windows8"; + var versionString = userAgent.match(/Windows (?:Phone |NT )?([0-9.]+)/)[1]; + + + + var Pnp = Windows.Devices.Enumeration.Pnp; + + Pnp.PnpObject.findAllAsync(Pnp.PnpObjectType.deviceContainer,[MANU_KEY]) + .then(function (infoList) { + var numDevices = infoList.length; + if (numDevices) { + for (var i = 0; i < numDevices; i++) { + var devContainer = infoList[i]; + if (devContainer.id == ROOT_CONTAINER) { + manufacturer = devContainer.properties[MANU_KEY]; + break; + } + } + } + }) + .then(function () { + Pnp.PnpObject.findAllAsync(Pnp.PnpObjectType.device, + [DEVICE_DRIVER_VERSION_KEY, DEVICE_CLASS_KEY], + ROOT_CONTAINER_QUERY) + .then(function (rootDevices) { + for (var i = 0; i < rootDevices.length; i++) { + var rootDevice = rootDevices[i]; + if (!rootDevice.properties) continue; + if (rootDevice.properties[DEVICE_CLASS_KEY_NO_SEMICOLON] == HAL_DEVICE_CLASS) { + versionString = rootDevice.properties[DEVICE_DRIVER_VERSION_KEY]; + break; + } + } + + setTimeout(function () { + win({ platform: devicePlatform, + version: versionString, + uuid: deviceId, + model: window.clientInformation.platform, + manufacturer:manufacturer}); + }, 0); + }); + }); + } + +}; // exports + +require("cordova/exec/proxy").add("Device", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-device/src/wp/Device.cs b/StoneIsland/plugins/cordova-plugin-device/src/wp/Device.cs new file mode 100644 index 00000000..897a35af --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/src/wp/Device.cs @@ -0,0 +1,135 @@ +/* + Licensed 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. +*/ + +using System; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; +using Microsoft.Phone.Info; +using System.IO.IsolatedStorage; +using System.Windows.Resources; +using System.IO; +using System.Diagnostics; + +namespace WPCordovaClassLib.Cordova.Commands +{ + public class Device : BaseCommand + { + public void getDeviceInfo(string notused) + { + + string res = String.Format("\"name\":\"{0}\",\"platform\":\"{1}\",\"uuid\":\"{2}\",\"version\":\"{3}\",\"model\":\"{4}\",\"manufacturer\":\"{5}\"", + this.name, + this.platform, + this.uuid, + this.version, + this.model, + this.manufacturer); + + res = "{" + res + "}"; + //Debug.WriteLine("Result::" + res); + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, res)); + } + + public string model + { + get + { + return DeviceStatus.DeviceName; + //return String.Format("{0},{1},{2}", DeviceStatus.DeviceManufacturer, DeviceStatus.DeviceHardwareVersion, DeviceStatus.DeviceFirmwareVersion); + } + } + + public string manufacturer + { + get + { + return DeviceStatus.DeviceManufacturer; + } + } + + public string name + { + get + { + return DeviceStatus.DeviceName; + + } + } + + public string platform + { + get + { + return Environment.OSVersion.Platform.ToString(); + } + } + + public string uuid + { + get + { + object id; + + UserExtendedProperties.TryGetValue("ANID", out id); + if (id != null) + { + return id.ToString().Substring(2, 32); + } + + UserExtendedProperties.TryGetValue("ANID2", out id); + if (id != null) + { + return id.ToString(); + } + + string returnVal = "???unknown???"; + + using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) + { + try + { + IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage); + + using (StreamReader reader = new StreamReader(fileStream)) + { + returnVal = reader.ReadLine(); + } + } + catch (Exception /*ex*/) + { + + } + } + + return returnVal; + } + } + + public string version + { + get + { + return Environment.OSVersion.Version.ToString(); + } + } + + } +} diff --git a/StoneIsland/plugins/cordova-plugin-device/tests/plugin.xml b/StoneIsland/plugins/cordova-plugin-device/tests/plugin.xml new file mode 100644 index 00000000..bcca190e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/tests/plugin.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + xmlns:rim="http://www.blackberry.com/ns/widgets" + xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-device-tests" + version="1.0.1"> + <name>Cordova Device Plugin Tests</name> + <license>Apache 2.0</license> + + <js-module src="tests.js" name="tests"> + </js-module> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-device/tests/tests.js b/StoneIsland/plugins/cordova-plugin-device/tests/tests.js new file mode 100644 index 00000000..1f49d7e1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/tests/tests.js @@ -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. + * +*/ + +exports.defineAutoTests = function() { + describe('Device Information (window.device)', function () { + it("should exist", function() { + expect(window.device).toBeDefined(); + }); + + it("should contain a platform specification that is a string", function() { + expect(window.device.platform).toBeDefined(); + expect((new String(window.device.platform)).length > 0).toBe(true); + }); + + it("should contain a version specification that is a string", function() { + expect(window.device.version).toBeDefined(); + expect((new String(window.device.version)).length > 0).toBe(true); + }); + + it("should contain a UUID specification that is a string or a number", function() { + expect(window.device.uuid).toBeDefined(); + if (typeof window.device.uuid == 'string' || typeof window.device.uuid == 'object') { + expect((new String(window.device.uuid)).length > 0).toBe(true); + } else { + expect(window.device.uuid > 0).toBe(true); + } + }); + + it("should contain a cordova specification that is a string", function() { + expect(window.device.cordova).toBeDefined(); + expect((new String(window.device.cordova)).length > 0).toBe(true); + }); + + it("should depend on the presence of cordova.version string", function() { + expect(window.cordova.version).toBeDefined(); + expect((new String(window.cordova.version)).length > 0).toBe(true); + }); + + it("should contain device.cordova equal to cordova.version", function() { + expect(window.device.cordova).toBe(window.cordova.version); + }); + + it("should contain a model specification that is a string", function() { + expect(window.device.model).toBeDefined(); + expect((new String(window.device.model)).length > 0).toBe(true); + }); + + it("should contain a manufacturer property that is a string", function() { + expect(window.device.manufacturer).toBeDefined(); + expect((new String(window.device.manufacturer)).length > 0).toBe(true); + }); + }); +}; + +exports.defineManualTests = function(contentEl, createActionButton) { + var logMessage = function (message, color) { + var log = document.getElementById('info'); + var logLine = document.createElement('div'); + if (color) { + logLine.style.color = color; + } + logLine.innerHTML = message; + log.appendChild(logLine); + } + + var clearLog = function () { + var log = document.getElementById('info'); + log.innerHTML = ''; + } + + var device_tests = '<h3>Press Dump Device button to get device information</h3>' + + '<div id="dump_device"></div>' + + 'Expected result: Status box will get updated with device info. (i.e. platform, version, uuid, model, etc)'; + + contentEl.innerHTML = '<div id="info"></div>' + device_tests; + + createActionButton('Dump device', function() { + clearLog(); + logMessage(JSON.stringify(window.device, null, '\t')); + }, "dump_device"); +}; diff --git a/StoneIsland/plugins/cordova-plugin-device/www/device.js b/StoneIsland/plugins/cordova-plugin-device/www/device.js new file mode 100644 index 00000000..b1d0d25d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-device/www/device.js @@ -0,0 +1,79 @@ +/* + * + * 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'), + channel = require('cordova/channel'), + utils = require('cordova/utils'), + exec = require('cordova/exec'), + 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; + + 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.manufacturer = info.manufacturer || '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/StoneIsland/plugins/cordova-plugin-dialogs/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-dialogs/CONTRIBUTING.md new file mode 100644 index 00000000..f7dbcaba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/LICENSE b/StoneIsland/plugins/cordova-plugin-dialogs/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/NOTICE b/StoneIsland/plugins/cordova-plugin-dialogs/NOTICE new file mode 100644 index 00000000..8ec56a52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/README.md new file mode 100644 index 00000000..b16b9f9a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +This plugin provides access to some native dialog UI elements +via a global `navigator.notification` object. + +Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + +## Installation + + cordova plugin add cordova-plugin-dialogs + +## Methods + +- `navigator.notification.alert` +- `navigator.notification.confirm` +- `navigator.notification.prompt` +- `navigator.notification.beep` + +## navigator.notification.alert + +Shows a custom alert or dialog box. Most Cordova implementations use a native +dialog box for this feature, but some platforms use the browser's `alert` +function, which is typically less customizable. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + +- __message__: Dialog message. _(String)_ + +- __alertCallback__: Callback to invoke when alert dialog is dismissed. _(Function)_ + +- __title__: Dialog title. _(String)_ (Optional, defaults to `Alert`) + +- __buttonName__: Button name. _(String)_ (Optional, defaults to `OK`) + + +### Example + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + +### Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Firefox OS +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 +- Windows + +### Windows Phone 7 and 8 Quirks + +- There is no built-in browser alert, but you can bind one as follows to call `alert()` in the global scope: + + window.alert = navigator.notification.alert; + +- Both `alert` and `confirm` are non-blocking calls, results of which are only available asynchronously. + +### Firefox OS Quirks: + +Both native-blocking `window.alert()` and non-blocking `navigator.notification.alert()` are available. + +### BlackBerry 10 Quirks +`navigator.notification.alert('text', callback, 'title', 'text')` callback parameter is passed the number 1. + +## navigator.notification.confirm + +Displays a customizable confirmation dialog box. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + +- __message__: Dialog message. _(String)_ + +- __confirmCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_ + +- __title__: Dialog title. _(String)_ (Optional, defaults to `Confirm`) + +- __buttonLabels__: Array of strings specifying button labels. _(Array)_ (Optional, defaults to [`OK,Cancel`]) + + +### confirmCallback + +The `confirmCallback` executes when the user presses one of the +buttons in the confirmation dialog box. + +The callback takes the argument `buttonIndex` _(Number)_, which is the +index of the pressed button. Note that the index uses one-based +indexing, so the value is `1`, `2`, `3`, etc. + +### Example + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + +### Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Firefox OS +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 +- Windows + +### Windows Phone 7 and 8 Quirks + +- There is no built-in browser function for `window.confirm`, but you can bind it by assigning: + + window.confirm = navigator.notification.confirm; + +- Calls to `alert` and `confirm` are non-blocking, so the result is only available asynchronously. + +### Windows Quirks + +- On Windows8/8.1 it is not possible to add more than three buttons to MessageDialog instance. + +- On Windows Phone 8.1 it's not possible to show dialog with more than two buttons. + +### Firefox OS Quirks: + +Both native-blocking `window.confirm()` and non-blocking `navigator.notification.confirm()` are available. + +## navigator.notification.prompt + +Displays a native dialog box that is more customizable than the browser's `prompt` function. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + +- __message__: Dialog message. _(String)_ + +- __promptCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_ + +- __title__: Dialog title _(String)_ (Optional, defaults to `Prompt`) + +- __buttonLabels__: Array of strings specifying button labels _(Array)_ (Optional, defaults to `["OK","Cancel"]`) + +- __defaultText__: Default textbox input value (`String`) (Optional, Default: empty string) + +### promptCallback + +The `promptCallback` executes when the user presses one of the buttons +in the prompt dialog box. The `results` object passed to the callback +contains the following properties: + +- __buttonIndex__: The index of the pressed button. _(Number)_ Note that the index uses one-based indexing, so the value is `1`, `2`, `3`, etc. + + + +- __input1__: The text entered in the prompt dialog box. _(String)_ + +### Example + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + +### Supported Platforms + +- Amazon Fire OS +- Android +- Firefox OS +- iOS +- Windows Phone 7 and 8 +- Windows 8 +- Windows + +### Android Quirks + +- Android supports a maximum of three buttons, and ignores any more than that. + +- On Android 3.0 and later, buttons are displayed in reverse order for devices that use the Holo theme. + +### Windows Quirks + +- On Windows prompt dialog is html-based due to lack of such native api. + +### Firefox OS Quirks: + +Both native-blocking `window.prompt()` and non-blocking `navigator.notification.prompt()` are available. + +## navigator.notification.beep + +The device plays a beep sound. + + navigator.notification.beep(times); + +- __times__: The number of times to repeat the beep. _(Number)_ + +### Example + + // Beep twice! + navigator.notification.beep(2); + +### Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 + +### Amazon Fire OS Quirks + +- Amazon Fire OS plays the default __Notification Sound__ specified under the __Settings/Display & Sound__ panel. + +### Android Quirks + +- Android plays the default __Notification ringtone__ specified under the __Settings/Sound & Display__ panel. + +### Windows Phone 7 and 8 Quirks + +- Relies on a generic beep file from the Cordova distribution. + +### Tizen Quirks + +- Tizen implements beeps by playing an audio file via the media API. + +- The beep file must be short, must be located in a `sounds` subdirectory of the application's root directory, and must be named `beep.wav`. + diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-dialogs/RELEASENOTES.md new file mode 100644 index 00000000..79571543 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/RELEASENOTES.md @@ -0,0 +1,139 @@ +<!-- +# +# 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. +# +--> +# Release Notes + +### 0.2.2 (Sept 25, 2013) +* CB-4889 bumping&resetting version +* [windows8] commandProxy was moved +* CB-4889 renaming reference in Notification.cs +* CB-4889 renaming org.apache.cordova.core.dialogs to org.apache.cordova.dialogs +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4592] [Blackberry10] Added beep support +* [CB-4752] Incremented plugin version on dev branch. + + ### 0.2.3 (Oct 28, 2013) +* CB-5128: added repo + issue tag to plugin.xml for dialogs plugin +* new plugin execute arguments supported +* new plugin style +* smaller fonts styling input +* img files copied inside plugin +* style added +* prompt added +* styling from James +* fixed "exec" calls addedd css, but not working yet +* first (blind) try +* [CB-4915] Incremented plugin version on dev branch. + + +### 0.2.4 (Dec 4, 2013) +* add ubuntu platform +* 1. Added amazon-fireos platform. 2. Change to use amazon-fireos as a platform if user agent string contains 'cordova-amazon-fireos'. +* added beep funtionality using ms-winsoundevent:Notfication.Default + +### 0.2.5 (Jan 02, 2014) +* CB-4696 Fix compile error for Xcode 4.5. +* CB-5658 Add doc/index.md for Dialogs plugin +* CB-3762 Change prompt default to empty string +* Move images from css to img + +### 0.2.6 (Feb 05, 2014) +* no need to recreate the manifest.webapp file after each `cordova prepare` for FFOS +* FFOS description added + +### 0.2.7 (Apr 17, 2014) +* CB-6212: [iOS] fix warnings compiled under arm64 64-bit +* CB-6411: [BlackBerry10] Work around Audio playback issue +* CB-6411: [BlackBerry10] Updates to beep +* CB-6422: [windows8] use cordova/exec/proxy +* CB-6460: Update license headers +* Add NOTICE file + +### 0.2.8 (Jun 05, 2014) +* CB-6801 Add license +* running original windows.open, inAppBrowser is overriding it no need to place CSS in every page anymore +* CB-5945 [Windows8] do not call success callbacks until dialog is dismissed +* CB-4616 Returned index 0 was not documented for notification.prompt +* update docs to state that prompt is supported on windowsphone +* CB-6528 allow scroll on alert message content +* [CB-6628][amazon-fireos]dialogs plugin's confirm and prompt methods dont work confirm() method was missing amazon-fireos platform check. added that. prompt() method had bug. It is executed in a worker thread that does not have a message queue(or Looper object) associated with it and hence "can't create a handler" exception is thrown. To fix this issue, we need to create the EditText widget from within the UI thread. This was fixed sometime ago when we added fireos platform but commit got lost somewhere. So fixing it again now. +* CB-6491 add CONTRIBUTING.md +* Added check for isFinishing() on the parent activity to prevent crashes when trying to display dialogs when activity is in this phase of it's lifecycle +* CB-4966 Dialogs are in window now No need to add anything to manifest or index.html +* Removing FirefoxOS Quirks * no need to add special permission (it's different API with the same name) * notification.css is added automatically + +### 0.2.9 (Aug 06, 2014) +* ubuntu: pass proper arguments to prompt callback +* ubuntu: use TextField instead of TextInput +* ubuntu: proper message escaping before passing to qml +* **FFOS** update notification.js +* CB-6127 Updated translations for docs +* android: Explicitly apply default theme to dialogs +* Fix Beep exception on Android when no argument passed + +### 0.2.10 (Sep 17, 2014) +* CB-7538 Android beep thread fix Beep now executes in it's own thread. It was previously executing in the main UI thread which was causing the application to lock up will the beep was occurring. Closing pull request +* Set dialog text dir to locale +* Renamed test dir, added nested plugin.xml +* added documentation for manual tests +* CB-6965 Added manual tests +* CB-6965 Port notification tests to test-framework + +### 0.2.11 (Dec 02, 2014) +* [CB-7737] lower min height for alert +* CB-8038 backslash getting escaped twice in **BB10** +* CB-8029 test 1-based indexing for confirm +* CB-7639 Update docs + manual tests +* CB-7639 Revert back `isAlertShowing` flag in case of exception to prevent queuing of future dialogs. +* CB-7639 Handle button labels as array on windows +* CB-7977 Mention `deviceready` in plugin docs +* Check for `setTextDirection` API level +* **Android** Make spinner dialog to use `THEME_DEVICE_DEFAULT_LIGHT` (same as the other dialogs) +* **Android** Unbreak `API` level < `14` +* CB-7414 **BB10** Document callback parameter for `navigator.notification.alert` +* CB-7700 cordova-plugin-dialogs documentation translation: cordova-plugin-dialogs +* CB-7571 Bump version of nested plugin to match parent plugin + +### 0.3.0 (Feb 04, 2015) +* Correct way to specify Windows platform in config.xml +* CB-8351 ios: Use argumentForIndex rather than NSArray extension +* CB-7955 Add support "browser" platform + +### 1.0.0 (Apr 15, 2015) +* CB-8746 gave plugin major version bump +* CB-8683 updated wp and bb specific references of old id to new id +* CB-8683 changed plugin-id to pacakge-name +* CB-8653 properly updated translated docs to use new id +* CB-8653 updated translated docs to use new id +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* CB-8653 Updated Readme +* CB-8659: ios: 4.0.x Compatibility: Remove use of deprecated headers +* CB-8565 Integrate TravisCI +* CB-8438 cordova-plugin-dialogs documentation translation: cordova-plugin-dialogs +* CB-8538 Added package.json file +* CB-8367 [org.apache.cordova.dialogs] Add Prompt support on Windows + +### 1.1.0 (May 06, 2015) +* CB-8928: Removed direct call to `toStaticHTML`, only call it if we are sure it's present. This closes #52 +* CB-7734 - `navigator.notification.alert` or `navigator.notification.confirm` seem have a "many words" issue. (closes #39) + +### 1.1.1 (Jun 17, 2015) +* CB-9128 cordova-plugin-dialogs documentation translation: cordova-plugin-dialogs +* fix npm md diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/de/README.md new file mode 100644 index 00000000..355cd4d1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/de/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +Dieses Plugin ermöglicht den Zugriff auf einige native Dialog-UI-Elemente über eine globale `navigator.notification`-Objekt. + +Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Installation + + cordova plugin add cordova-plugin-dialogs + + +## Methoden + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +Zeigt eine benutzerdefinierte Warnung oder Dialogfeld Feld. Die meisten Implementierungen von Cordova ein native Dialogfeld für dieses Feature verwenden, jedoch einige Plattformen des Browsers-`alert`-Funktion, die in der Regel weniger anpassbar ist. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **Nachricht**: Dialogfeld Nachricht. *(String)* + + * **AlertCallback**: Callback aufgerufen wird, wenn Warnungs-Dialogfeld geschlossen wird. *(Funktion)* + + * **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Alert`) + + * **ButtonName**: Name der Schaltfläche. *(String)* (Optional, Standard ist`OK`) + +### Beispiel + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + * Windows + +### Windows Phone 7 und 8 Eigenarten + + * Es gibt keine eingebaute Datenbanksuchroutine-Warnung, aber Sie können binden, wie folgt zu nennen `alert()` im globalen Gültigkeitsbereich: + + window.alert = navigator.notification.alert; + + + * Beide `alert` und `confirm` sind nicht blockierende Aufrufe, die Ergebnisse davon nur asynchron sind. + +### Firefox OS Macken: + +Native blockierenden `window.alert()` und nicht-blockierende `navigator.notification.alert()` zur Verfügung. + +### BlackBerry 10 Macken + +`navigator.notification.alert ('Text', Rückruf, 'Titel', 'Text')` Callback-Parameter wird die Zahl 1 übergeben. + +## navigator.notification.confirm + +Zeigt das Dialogfeld anpassbare Bestätigung. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **Nachricht**: Dialogfeld Nachricht. *(String)* + + * **ConfirmCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)* + + * **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Confirm`) + + * **ButtonLabels**: Array von Zeichenfolgen, die Schaltflächenbezeichnungen angeben. *(Array)* (Optional, Standard ist [ `OK,Cancel` ]) + +### confirmCallback + +Die `confirmCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Dialogfeld zur Bestätigung drückt. + +Der Rückruf dauert das Argument `buttonIndex` *(Anzahl)*, die der Index der Schaltfläche gedrückt ist. Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist. + +### Beispiel + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + * Windows + +### Windows Phone 7 und 8 Eigenarten + + * Es gibt keine integrierte Browser-Funktion für `window.confirm` , aber Sie können es binden, indem Sie zuweisen: + + window.confirm = navigator.notification.confirm; + + + * Aufrufe von `alert` und `confirm` sind nicht blockierend, so dass das Ergebnis nur asynchron zur Verfügung steht. + +### Windows-Eigenheiten + + * Auf Windows8/8.1 kann nicht mehr als drei Schaltflächen MessageDialog-Instanz hinzu. + + * Auf Windows Phone 8.1 ist es nicht möglich, Dialog mit mehr als zwei Knöpfen zeigen. + +### Firefox OS Macken: + +Native blockierenden `window.confirm()` und nicht-blockierende `navigator.notification.confirm()` zur Verfügung. + +## navigator.notification.prompt + +Zeigt eine native Dialogfeld, das mehr als `Prompt`-Funktion des Browsers anpassbar ist. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **Nachricht**: Dialogfeld Nachricht. *(String)* + + * **promptCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)* + + * **title**: Dialog Title *(String)* (Optional, Standard ist `Prompt`) + + * **buttonLabels**: Array von Zeichenfolgen angeben Schaltfläche Etiketten *(Array)* (Optional, Standard ist `["OK", "Abbrechen"]`) + + * **defaultText**: Standard-Textbox Eingabewert (`String`) (Optional, Standard: leere Zeichenfolge) + +### promptCallback + +Die `promptCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Eingabedialogfeld drückt. `Des Objekts an den Rückruf übergeben` enthält die folgenden Eigenschaften: + + * **buttonIndex**: der Index der Schaltfläche gedrückt. *(Anzahl)* Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist. + + * **input1**: in Eingabedialogfeld eingegebenen Text. *(String)* + +### Beispiel + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### Unterstützte Plattformen + + * Amazon Fire OS + * Android + * Firefox OS + * iOS + * Windows Phone 7 und 8 + * Windows 8 + * Windows + +### Android Eigenarten + + * Android unterstützt maximal drei Schaltflächen und mehr als das ignoriert. + + * Auf Android 3.0 und höher, werden die Schaltflächen in umgekehrter Reihenfolge für Geräte angezeigt, die das Holo-Design verwenden. + +### Windows-Eigenheiten + + * Unter Windows ist Prompt Dialogfeld html-basierten mangels solcher native api. + +### Firefox OS Macken: + +Native blockierenden `window.prompt()` und nicht-blockierende `navigator.notification.prompt()` zur Verfügung. + +## navigator.notification.beep + +Das Gerät spielt einen Signalton sound. + + navigator.notification.beep(times); + + + * **times**: die Anzahl der Wiederholungen des Signaltons. *(Anzahl)* + +### Beispiel + + // Beep twice! + navigator.notification.beep(2); + + +### Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + +### Amazon Fire OS Macken + + * Amazon Fire OS spielt die Standardeinstellung **Akustische Benachrichtigung** unter **Einstellungen/Display & Sound** Bereich angegeben. + +### Android Eigenarten + + * Android spielt die Standardeinstellung **Benachrichtigung Klingelton** unter **Einstellungen/Sound & Display**-Panel angegeben. + +### Windows Phone 7 und 8 Eigenarten + + * Stützt sich auf eine generische Piepton-Datei aus der Cordova-Distribution. + +### Tizen Macken + + * Tizen implementiert Signaltöne durch Abspielen einer Audiodatei über die Medien API. + + * Die Beep-Datei muss kurz sein, in einem `sounds`-Unterverzeichnis des Stammverzeichnisses der Anwendung befinden muss und muss den Namen `beep.wav`.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/de/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/de/index.md new file mode 100644 index 00000000..c003d401 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/de/index.md @@ -0,0 +1,273 @@ +<!--- + 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-plugin-dialogs + +Dieses Plugin ermöglicht den Zugriff auf einige native Dialog-UI-Elemente über eine globale `navigator.notification`-Objekt. + +Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Installation + + cordova plugin add cordova-plugin-dialogs + + +## Methoden + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +Zeigt eine benutzerdefinierte Warnung oder Dialogfeld Feld. Die meisten Implementierungen von Cordova ein native Dialogfeld für dieses Feature verwenden, jedoch einige Plattformen des Browsers-`alert`-Funktion, die in der Regel weniger anpassbar ist. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + +* **Nachricht**: Dialogfeld Nachricht. *(String)* + +* **AlertCallback**: Callback aufgerufen wird, wenn Warnungs-Dialogfeld geschlossen wird. *(Funktion)* + +* **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Alert`) + +* **ButtonName**: Name der Schaltfläche. *(String)* (Optional, Standard ist`OK`) + +### Beispiel + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 +* Windows + +### Windows Phone 7 und 8 Eigenarten + +* Es gibt keine eingebaute Datenbanksuchroutine-Warnung, aber Sie können binden, wie folgt zu nennen `alert()` im globalen Gültigkeitsbereich: + + window.alert = navigator.notification.alert; + + +* Beide `alert` und `confirm` sind nicht blockierende Aufrufe, die Ergebnisse davon nur asynchron sind. + +### Firefox OS Macken: + +Native blockierenden `window.alert()` und nicht-blockierende `navigator.notification.alert()` zur Verfügung. + +### BlackBerry 10 Macken + +`navigator.notification.alert ('Text', Rückruf, 'Titel', 'Text')` Callback-Parameter wird die Zahl 1 übergeben. + +## navigator.notification.confirm + +Zeigt das Dialogfeld anpassbare Bestätigung. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **Nachricht**: Dialogfeld Nachricht. *(String)* + +* **ConfirmCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)* + +* **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Confirm`) + +* **ButtonLabels**: Array von Zeichenfolgen, die Schaltflächenbezeichnungen angeben. *(Array)* (Optional, Standard ist [ `OK,Cancel` ]) + +### confirmCallback + +Die `confirmCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Dialogfeld zur Bestätigung drückt. + +Der Rückruf dauert das Argument `buttonIndex` *(Anzahl)*, die der Index der Schaltfläche gedrückt ist. Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist. + +### Beispiel + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 +* Windows + +### Windows Phone 7 und 8 Eigenarten + +* Es gibt keine integrierte Browser-Funktion für `window.confirm` , aber Sie können es binden, indem Sie zuweisen: + + window.confirm = navigator.notification.confirm; + + +* Aufrufe von `alert` und `confirm` sind nicht blockierend, so dass das Ergebnis nur asynchron zur Verfügung steht. + +### Windows-Eigenheiten + +* Auf Windows8/8.1 kann nicht mehr als drei Schaltflächen MessageDialog-Instanz hinzu. + +* Auf Windows Phone 8.1 ist es nicht möglich, Dialog mit mehr als zwei Knöpfen zeigen. + +### Firefox OS Macken: + +Native blockierenden `window.confirm()` und nicht-blockierende `navigator.notification.confirm()` zur Verfügung. + +## navigator.notification.prompt + +Zeigt eine native Dialogfeld, das mehr als `Prompt`-Funktion des Browsers anpassbar ist. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **Nachricht**: Dialogfeld Nachricht. *(String)* + +* **promptCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)* + +* **title**: Dialog Title *(String)* (Optional, Standard ist `Prompt`) + +* **buttonLabels**: Array von Zeichenfolgen angeben Schaltfläche Etiketten *(Array)* (Optional, Standard ist `["OK", "Abbrechen"]`) + +* **defaultText**: Standard-Textbox Eingabewert (`String`) (Optional, Standard: leere Zeichenfolge) + +### promptCallback + +Die `promptCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Eingabedialogfeld drückt. `Des Objekts an den Rückruf übergeben` enthält die folgenden Eigenschaften: + +* **buttonIndex**: der Index der Schaltfläche gedrückt. *(Anzahl)* Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist. + +* **input1**: in Eingabedialogfeld eingegebenen Text. *(String)* + +### Beispiel + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### Unterstützte Plattformen + +* Amazon Fire OS +* Android +* Firefox OS +* iOS +* Windows Phone 7 und 8 +* Windows 8 +* Windows + +### Android Eigenarten + +* Android unterstützt maximal drei Schaltflächen und mehr als das ignoriert. + +* Auf Android 3.0 und höher, werden die Schaltflächen in umgekehrter Reihenfolge für Geräte angezeigt, die das Holo-Design verwenden. + +### Windows-Eigenheiten + +* Unter Windows ist Prompt Dialogfeld html-basierten mangels solcher native api. + +### Firefox OS Macken: + +Native blockierenden `window.prompt()` und nicht-blockierende `navigator.notification.prompt()` zur Verfügung. + +## navigator.notification.beep + +Das Gerät spielt einen Signalton sound. + + navigator.notification.beep(times); + + +* **times**: die Anzahl der Wiederholungen des Signaltons. *(Anzahl)* + +### Beispiel + + // Beep twice! + navigator.notification.beep(2); + + +### Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +### Amazon Fire OS Macken + +* Amazon Fire OS spielt die Standardeinstellung **Akustische Benachrichtigung** unter **Einstellungen/Display & Sound** Bereich angegeben. + +### Android Eigenarten + +* Android spielt die Standardeinstellung **Benachrichtigung Klingelton** unter **Einstellungen/Sound & Display**-Panel angegeben. + +### Windows Phone 7 und 8 Eigenarten + +* Stützt sich auf eine generische Piepton-Datei aus der Cordova-Distribution. + +### Tizen Macken + +* Tizen implementiert Signaltöne durch Abspielen einer Audiodatei über die Medien API. + +* Die Beep-Datei muss kurz sein, in einem `sounds`-Unterverzeichnis des Stammverzeichnisses der Anwendung befinden muss und muss den Namen `beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/es/README.md new file mode 100644 index 00000000..e7df5fea --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/es/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +Este plugin permite acceder a algunos elementos de interfaz de usuario nativa diálogo vÃa global `navigator.notification` objeto. + +Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Instalación + + cordova plugin add cordova-plugin-dialogs + + +## Métodos + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +Muestra un cuadro de alerta o cuadro de diálogo personalizado. La mayorÃa de las implementaciones de Cordova utilizan un cuadro de diálogo nativa para esta caracterÃstica, pero algunas plataformas utilizan el navegador `alert` la función, que es tÃpicamente menos personalizable. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **message**: mensaje de diálogo. *(String)* + + * **alertCallback**: Callback para invocar al diálogo de alerta es desestimada. *(Función)* + + * **title**: tÃtulo de diálogo. *(String)* (Opcional, el valor predeterminado de `Alert`) + + * **buttonName**: nombre del botón. *(String)* (Opcional, por defecto `Aceptar`) + +### Ejemplo + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + * Windows + +### Windows Phone 7 y 8 rarezas + + * No hay ninguna alerta del navegador integrado, pero puede enlazar uno proceda a llamar `alert()` en el ámbito global: + + window.alert = navigator.notification.alert; + + + * `alert` y `confirm` son non-blocking llamadas, cuyos resultados sólo están disponibles de forma asincrónica. + +### Firefox OS rarezas: + +Dos nativos de bloqueo `window.alert()` y no-bloqueo `navigator.notification.alert()` están disponibles. + +### BlackBerry 10 rarezas + +`navigator.notification.alert('text', callback, 'title', 'text')`parámetro de devolución de llamada se pasa el número 1. + +## navigator.notification.confirm + +Muestra un cuadro de diálogo de confirmación personalizables. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **message**: mensaje de diálogo. *(String)* + + * **confirmCallback**: Callback para invocar con Ãndice de botón pulsado (1, 2 o 3) o cuando el diálogo es despedido sin la presión del botón (0). *(Función)* + + * **title**: tÃtulo de diálogo. *(String)* (Opcional, por defecto a `confirmar`) + + * **buttonLabels**: matriz de cadenas especificando las etiquetas de botón. *(Matriz)* (Opcional, por defecto [`OK, cancelar`]) + +### confirmCallback + +El `confirmCallback` se ejecuta cuando el usuario presiona uno de los botones en el cuadro de diálogo de confirmación. + +La devolución de llamada toma el argumento `buttonIndex` *(número)*, que es el Ãndice del botón presionado. Observe que el Ãndice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc.. + +### Ejemplo + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + * Windows + +### Windows Phone 7 y 8 rarezas + + * No hay ninguna función de navegador incorporado para `window.confirm`, pero lo puede enlazar mediante la asignación: + + window.confirm = navigator.notification.confirm; + + + * Llamadas de `alert` y `confirm` son non-blocking, asà que el resultado sólo está disponible de forma asincrónica. + +### Windows rarezas + + * Sobre Windows8/8.1 no es posible agregar más de tres botones a instancia de MessageDialog. + + * En Windows Phone 8.1 no es posible Mostrar cuadro de diálogo con más de dos botones. + +### Firefox OS rarezas: + +Dos nativos de bloqueo `window.confirm()` y no-bloqueo `navigator.notification.confirm()` están disponibles. + +## navigator.notification.prompt + +Muestra un cuadro de diálogo nativa que es más personalizable que del navegador `prompt` función. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **message**: mensaje de diálogo. *(String)* + + * **promptCallback**: Callback para invocar con Ãndice del botón pulsado (1, 2 ó 3) o cuando el cuadro de diálogo es despedido sin la presión del botón (0). *(Función)* + + * **tÃtulo**: tÃtulo *(String)* (opcional, por defecto de diálogo`Prompt`) + + * **buttonLabels**: matriz de cadenas especificando botón etiquetas *(Array)* (opcional, por defecto`["OK","Cancel"]`) + + * **defaultText**: valor de la entrada predeterminada textbox ( `String` ) (opcional, por defecto: cadena vacÃa) + +### promptCallback + +El `promptCallback` se ejecuta cuando el usuario presiona uno de los botones del cuadro de diálogo pronto. El `results` objeto que se pasa a la devolución de llamada contiene las siguientes propiedades: + + * **buttonIndex**: el Ãndice del botón presionado. *(Número)* Observe que el Ãndice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc.. + + * **INPUT1**: el texto introducido en el cuadro de diálogo pronto. *(String)* + +### Ejemplo + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### Plataformas soportadas + + * Amazon fire OS + * Android + * Firefox OS + * iOS + * Windows Phone 7 y 8 + * Windows 8 + * Windows + +### Rarezas Android + + * Android soporta un máximo de tres botones e ignora nada más. + + * En Android 3.0 y posteriores, los botones aparecen en orden inverso para dispositivos que utilizan el tema Holo. + +### Windows rarezas + + * En Windows pronto diálogo está basado en html debido a falta de tal api nativa. + +### Firefox OS rarezas: + +Dos nativos de bloqueo `window.prompt()` y no-bloqueo `navigator.notification.prompt()` están disponibles. + +## navigator.notification.beep + +El aparato reproduce un sonido sonido. + + navigator.notification.beep(times); + + + * **tiempos**: el número de veces a repetir la señal. *(Número)* + +### Ejemplo + + // Beep twice! + navigator.notification.beep(2); + + +### Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + +### Amazon fuego OS rarezas + + * Amazon fuego OS reproduce el **Sonido de notificación** especificados en el panel de **configuración/pantalla y sonido** por defecto. + +### Rarezas Android + + * Androide reproduce el **tono de notificación** especificados en el panel **ajustes de sonido y visualización** por defecto. + +### Windows Phone 7 y 8 rarezas + + * Se basa en un archivo de sonido genérico de la distribución de Córdoba. + +### Rarezas Tizen + + * Tizen implementa pitidos por reproducir un archivo de audio a través de los medios de comunicación API. + + * El archivo de sonido debe ser corto, debe estar ubicado en un `sounds` subdirectorio del directorio raÃz de la aplicación y deben ser nombrados`beep.wav`.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/es/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/es/index.md new file mode 100644 index 00000000..9ff4251e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/es/index.md @@ -0,0 +1,247 @@ +<!--- + 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-plugin-dialogs + +Este plugin permite acceder a algunos elementos de interfaz de usuario nativa diálogo vÃa global `navigator.notification` objeto. + +Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log(navigator.notification)}; + + +## Instalación + + Cordova plugin agregar cordova-plugin-dialogs + + +## Métodos + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +Muestra un cuadro de alerta o cuadro de diálogo personalizado. La mayorÃa de las implementaciones de Cordova utilizan un cuadro de diálogo nativa para esta caracterÃstica, pero algunas plataformas utilizan el navegador `alert` la función, que es tÃpicamente menos personalizable. + + Navigator.Notification.alert (mensaje, alertCallback, [title], [buttonName]) + + +* **message**: mensaje de diálogo. *(String)* + +* **alertCallback**: Callback para invocar al diálogo de alerta es desestimada. *(Función)* + +* **title**: tÃtulo de diálogo. *(String)* (Opcional, el valor predeterminado de `Alert`) + +* **buttonName**: nombre del botón. *(String)* (Opcional, por defecto `Aceptar`) + +### Ejemplo + + function alertDismissed() {/ / hacer algo} navigator.notification.alert ('Tú eres el ganador!', / / mensaje alertDismissed, / / callback 'Game Over', / / tÃtulo 'hecho' / / buttonName); + + +### Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 +* Windows + +### Windows Phone 7 y 8 rarezas + +* No hay ninguna alerta del navegador integrado, pero puede enlazar uno proceda a llamar `alert()` en el ámbito global: + + window.alert = navigator.notification.alert; + + +* `alert` y `confirm` son non-blocking llamadas, cuyos resultados sólo están disponibles de forma asincrónica. + +### Firefox OS rarezas: + +Dos nativos de bloqueo `window.alert()` y no-bloqueo `navigator.notification.alert()` están disponibles. + +### BlackBerry 10 rarezas + +`navigator.notification.alert('text', callback, 'title', 'text')`parámetro de devolución de llamada se pasa el número 1. + +## navigator.notification.confirm + +Muestra un cuadro de diálogo de confirmación personalizables. + + Navigator.Notification.CONFIRM (mensaje, confirmCallback, [title], [buttonLabels]) + + +* **message**: mensaje de diálogo. *(String)* + +* **confirmCallback**: Callback para invocar con Ãndice de botón pulsado (1, 2 o 3) o cuando el diálogo es despedido sin la presión del botón (0). *(Función)* + +* **title**: tÃtulo de diálogo. *(String)* (Opcional, por defecto a `confirmar`) + +* **buttonLabels**: matriz de cadenas especificando las etiquetas de botón. *(Matriz)* (Opcional, por defecto [`OK, cancelar`]) + +### confirmCallback + +El `confirmCallback` se ejecuta cuando el usuario presiona uno de los botones en el cuadro de diálogo de confirmación. + +La devolución de llamada toma el argumento `buttonIndex` *(número)*, que es el Ãndice del botón presionado. Observe que el Ãndice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc.. + +### Ejemplo + + function onConfirm(buttonIndex) {alert ('Tu botón seleccionado' + buttonIndex);} + + Navigator.Notification.CONFIRM ('Tú eres el ganador!', / / mensaje onConfirm, / callback para invocar con Ãndice del botón pulsado 'Game Over', / / / tÃtulo ['reiniciar', 'Exit'] / / buttonLabels); + + +### Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 +* Windows + +### Windows Phone 7 y 8 rarezas + +* No hay ninguna función de navegador incorporado para `window.confirm`, pero lo puede enlazar mediante la asignación: + + window.confirm = navigator.notification.confirm; + + +* Llamadas de `alert` y `confirm` son non-blocking, asà que el resultado sólo está disponible de forma asincrónica. + +### Windows rarezas + +* Sobre Windows8/8.1 no es posible agregar más de tres botones a instancia de MessageDialog. + +* En Windows Phone 8.1 no es posible Mostrar cuadro de diálogo con más de dos botones. + +### Firefox OS rarezas: + +Dos nativos de bloqueo `window.confirm()` y no-bloqueo `navigator.notification.confirm()` están disponibles. + +## navigator.notification.prompt + +Muestra un cuadro de diálogo nativa que es más personalizable que del navegador `prompt` función. + + Navigator.Notification.prompt (mensaje, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **mensaje**: mensaje de diálogo. *(String)* + +* **promptCallback**: Callback para invocar con Ãndice del botón pulsado (1, 2 ó 3) o cuando el cuadro de diálogo es despedido sin la presión del botón (0). *(Función)* + +* **tÃtulo**: tÃtulo *(String)* (opcional, por defecto de diálogo`Prompt`) + +* **buttonLabels**: matriz de cadenas especificando botón etiquetas *(Array)* (opcional, por defecto`["OK","Cancel"]`) + +* **defaultText**: valor de la entrada predeterminada textbox ( `String` ) (opcional, por defecto: cadena vacÃa) + +### promptCallback + +El `promptCallback` se ejecuta cuando el usuario presiona uno de los botones del cuadro de diálogo pronto. El `results` objeto que se pasa a la devolución de llamada contiene las siguientes propiedades: + +* **buttonIndex**: el Ãndice del botón presionado. *(Número)* Observe que el Ãndice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc.. + +* **INPUT1**: el texto introducido en el cuadro de diálogo pronto. *(String)* + +### Ejemplo + + function onPrompt(results) {alert ("seleccionaron botón número" + results.buttonIndex + "y entró en" + results.input1);} + + Navigator.Notification.prompt ('Por favor introduce tu nombre', / / mensaje onPrompt, / / callback para invocar 'Registro', / / tÃtulo ['Ok', 'Exit'], / / buttonLabels 'Jane Doe' / / defaultText); + + +### Plataformas soportadas + +* Amazon fuego OS +* Android +* Firefox OS +* iOS +* Windows Phone 7 y 8 +* Windows 8 +* Windows + +### Rarezas Android + +* Android soporta un máximo de tres botones e ignora nada más. + +* En Android 3.0 y posteriores, los botones aparecen en orden inverso para dispositivos que utilizan el tema Holo. + +### Windows rarezas + +* En Windows pronto diálogo está basado en html debido a falta de tal api nativa. + +### Firefox OS rarezas: + +Dos nativos de bloqueo `window.prompt()` y no-bloqueo `navigator.notification.prompt()` están disponibles. + +## navigator.notification.beep + +El aparato reproduce un sonido sonido. + + Navigator.Notification.Beep(Times); + + +* **tiempos**: el número de veces a repetir la señal. *(Número)* + +### Ejemplo + + Dos pitidos. + Navigator.Notification.Beep(2); + + +### Plataformas soportadas + +* Amazon fuego OS +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +### Amazon fuego OS rarezas + +* Amazon fuego OS reproduce el **Sonido de notificación** especificados en el panel de **configuración/pantalla y sonido** por defecto. + +### Rarezas Android + +* Androide reproduce el **tono de notificación** especificados en el panel **ajustes de sonido y visualización** por defecto. + +### Windows Phone 7 y 8 rarezas + +* Se basa en un archivo de sonido genérico de la distribución de Córdoba. + +### Rarezas Tizen + +* Tizen implementa pitidos por reproducir un archivo de audio a través de los medios de comunicación API. + +* El archivo de sonido debe ser corto, debe estar ubicado en un `sounds` subdirectorio del directorio raÃz de la aplicación y deben ser nombrados`beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/fr/README.md new file mode 100644 index 00000000..994c8264 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/fr/README.md @@ -0,0 +1,249 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +Ce plugin permet d'accéder à certains éléments d'interface utilisateur native de dialogue via un global `navigator.notification` objet. + +Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log(navigator.notification);} + + +## Installation + + cordova plugin add cordova-plugin-dialogs + + +## Méthodes + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +Affiche une boîte de dialogue ou d'alerte personnalisé. La plupart des implémentations de Cordova utilisent une boîte de dialogue natives pour cette fonctionnalité, mais certaines plates-formes du navigateur `alert` fonction, qui est généralement moins personnalisable. + + Navigator.notification.Alert (message, alertCallback, [title], [buttonName]) + + + * **message**: message de la boîte de dialogue. *(String)* + + * **alertCallback**: callback à appeler lorsque la boîte de dialogue d'alerte est rejetée. *(Fonction)* + + * **titre**: titre de la boîte de dialogue. *(String)* (Facultatif, par défaut`Alert`) + + * **buttonName**: nom du bouton. *(String)* (Facultatif, par défaut`OK`) + +### Exemple + + function alertDismissed() {/ / faire quelque chose} navigator.notification.alert ('Vous êtes le gagnant!', / / message alertDismissed, / / rappel « Game Over », / / titre « Done » / / buttonName) ; + + +### Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + * Windows + +### Notes au sujet de Windows Phone 7 et 8 + + * Il n'y a aucune boîte de dialogue d'alerte intégrée au navigateur, mais vous pouvez en lier une pour appeler `alert()` dans le scope global: + + window.alert = navigator.notification.alert; + + + * Les deux appels `alert` et `confirm` sont non-blocants, leurs résultats ne sont disponibles que de façon asynchrone. + +### Firefox OS Quirks : + +Les deux indigènes bloquant `window.alert()` et non-bloquante `navigator.notification.alert()` sont disponibles. + +### BlackBerry 10 Quirks + +`navigator.notification.alert('text', callback, 'title', 'text')`paramètre callback est passé numéro 1. + +## navigator.notification.confirm + +Affiche une boîte de dialogue de confirmation personnalisable. + + Navigator.notification.Confirm (message, confirmCallback, [title], [buttonLabels]) + + + * **message**: message de la boîte de dialogue. *(String)* + + * **confirmCallback**: callback à appeler avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans qu'un bouton ne soit pressé (0). *(Fonction)* + + * **titre**: titre de dialogue. *(String)* (Facultatif, par défaut`Confirm`) + + * **buttonLabels**: tableau de chaînes spécifiant les étiquettes des boutons. *(Array)* (Optionnel, par défaut, [ `OK,Cancel` ]) + +### confirmCallback + +Le `confirmCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue de confirmation. + +Le rappel prend l'argument `buttonIndex` *(nombre)*, qui est l'index du bouton activé. Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc.. + +### Exemple + + function onConfirm(buttonIndex) {alert (« Vous bouton sélectionné » + buttonIndex);} + + Navigator.notification.Confirm ('Vous êtes le gagnant!', / / message onConfirm, / / rappel d'invoquer avec l'index du bouton enfoncé « Game Over », / / title ['redémarrer', « Exit »] / / buttonLabels) ; + + +### Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + * Windows + +### Notes au sujet de Windows Phone 7 et 8 + + * Il n'y a aucune fonction intégrée au navigateur pour `window.confirm`, mais vous pouvez en lier une en affectant: + + window.confirm = navigator.notification.confirm ; + + + * Les appels à `alert` et `confirm` sont non-bloquants, donc le résultat est seulement disponible de façon asynchrone. + +### Bizarreries de Windows + + * Sur Windows8/8.1, il n'est pas possible d'ajouter plus de trois boutons à MessageDialog instance. + + * Sur Windows Phone 8.1, il n'est pas possible d'établir le dialogue avec plus de deux boutons. + +### Firefox OS Quirks : + +Les deux indigènes bloquant `window.confirm()` et non-bloquante `navigator.notification.confirm()` sont disponibles. + +## navigator.notification.prompt + +Affiche une boîte de dialogue natif qui est plus personnalisable que le navigateur `prompt` fonction. + + Navigator.notification.prompt (message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **message**: message de la boîte de dialogue. *(String)* + + * **promptCallback**: rappel d'invoquer avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans une presse de bouton (0). *(Fonction)* + + * **titre**: titre *(String)* (facultatif, la valeur par défaut de dialogue`Prompt`) + + * **buttonLabels**: tableau de chaînes spécifiant les bouton *(Array)* (facultatif, par défaut, les étiquettes`["OK","Cancel"]`) + + * **defaultText**: zone de texte par défaut entrée valeur ( `String` ) (en option, par défaut : chaîne vide) + +### promptCallback + +Le `promptCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue d'invite. Le `results` objet passé au rappel contient les propriétés suivantes : + + * **buttonIndex**: l'index du bouton activé. *(Nombre)* Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc.. + + * **entrée 1**: le texte entré dans la boîte de dialogue d'invite. *(String)* + +### Exemple + + function onPrompt(results) {alert (« Vous avez sélectionné le numéro du bouton » + results.buttonIndex + « et saisi » + results.input1);} + + Navigator.notification.prompt ('Veuillez saisir votre nom', / / message onPrompt, / / rappel à appeler « Registration », / / title ['Ok', 'Exit'], / / buttonLabels « Jane Doe » / / defaultText) ; + + +### Plates-formes supportées + + * Amazon Fire OS + * Android + * Firefox OS + * iOS + * Windows Phone 7 et 8 + * Windows 8 + * Windows + +### Quirks Android + + * Android prend en charge un maximum de trois boutons et ignore plus que cela. + + * Sur Android 3.0 et versions ultérieures, les boutons sont affichés dans l'ordre inverse pour les appareils qui utilisent le thème Holo. + +### Bizarreries de Windows + + * Sous Windows, dialogue d'invite est basé sur html en raison de l'absence de ces api native. + +### Firefox OS Quirks : + +Les deux indigènes bloquant `window.prompt()` et non-bloquante `navigator.notification.prompt()` sont disponibles. + +## navigator.notification.beep + +Le dispositif joue un bip sonore. + + Navigator.notification.Beep(Times) ; + + + * **temps**: le nombre de fois répéter le bip. *(Nombre)* + +### Exemple + + Deux bips ! + Navigator.notification.Beep(2) ; + + +### Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + +### Amazon Fire OS Quirks + + * Amazon Fire OS joue la valeur par défaut le **Son de Notification** spécifié sous le panneau **d'affichage des réglages/& Sound** . + +### Quirks Android + + * Android joue la **sonnerie de Notification** spécifié sous le panneau des **réglages/son et affichage** de valeur par défaut. + +### Notes au sujet de Windows Phone 7 et 8 + + * S'appuie sur un fichier générique bip de la distribution de Cordova. + +### Bizarreries de paciarelli + + * Paciarelli implémente les bips en lisant un fichier audio via les médias API. + + * Le fichier sonore doit être court, doit se trouver dans un `sounds` sous-répertoire du répertoire racine de l'application et doit être nommé`beep.wav`.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/fr/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/fr/index.md new file mode 100644 index 00000000..fec09396 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/fr/index.md @@ -0,0 +1,247 @@ +<!--- + 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-plugin-dialogs + +Ce plugin permet d'accéder à certains éléments d'interface utilisateur native de dialogue via un global `navigator.notification` objet. + +Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log(navigator.notification);} + + +## Installation + + Cordova plugin ajouter cordova-plugin-dialogs + + +## Méthodes + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +Affiche une boîte de dialogue ou d'alerte personnalisé. La plupart des implémentations de Cordova utilisent une boîte de dialogue natives pour cette fonctionnalité, mais certaines plates-formes du navigateur `alert` fonction, qui est généralement moins personnalisable. + + Navigator.notification.Alert (message, alertCallback, [title], [buttonName]) + + +* **message**: message de la boîte de dialogue. *(String)* + +* **alertCallback**: callback à appeler lorsque la boîte de dialogue d'alerte est rejetée. *(Fonction)* + +* **titre**: titre de la boîte de dialogue. *(String)* (Facultatif, par défaut`Alert`) + +* **buttonName**: nom du bouton. *(String)* (Facultatif, par défaut`OK`) + +### Exemple + + function alertDismissed() {/ / faire quelque chose} navigator.notification.alert ('Vous êtes le gagnant!', / / message alertDismissed, / / rappel « Game Over », / / titre « Done » / / buttonName) ; + + +### Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 et 8 +* Windows 8 +* Windows + +### Windows Phone 7 et 8 Quirks + +* Il n'y a aucune boîte de dialogue d'alerte intégrée au navigateur, mais vous pouvez en lier une pour appeler `alert()` dans le scope global: + + window.alert = navigator.notification.alert; + + +* Les deux appels `alert` et `confirm` sont non-blocants, leurs résultats ne sont disponibles que de façon asynchrone. + +### Firefox OS Quirks : + +Les deux indigènes bloquant `window.alert()` et non-bloquante `navigator.notification.alert()` sont disponibles. + +### BlackBerry 10 Quirks + +`navigator.notification.alert('text', callback, 'title', 'text')`paramètre callback est passé numéro 1. + +## navigator.notification.confirm + +Affiche une boîte de dialogue de confirmation personnalisable. + + Navigator.notification.Confirm (message, confirmCallback, [title], [buttonLabels]) + + +* **message**: message de la boîte de dialogue. *(String)* + +* **confirmCallback**: callback à appeler avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans qu'un bouton ne soit pressé (0). *(Fonction)* + +* **titre**: titre de dialogue. *(String)* (Facultatif, par défaut`Confirm`) + +* **buttonLabels**: tableau de chaînes spécifiant les étiquettes des boutons. *(Array)* (Optionnel, par défaut, [ `OK,Cancel` ]) + +### confirmCallback + +Le `confirmCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue de confirmation. + +Le rappel prend l'argument `buttonIndex` *(nombre)*, qui est l'index du bouton activé. Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc.. + +### Exemple + + function onConfirm(buttonIndex) {alert (« Vous bouton sélectionné » + buttonIndex);} + + Navigator.notification.Confirm ('Vous êtes le gagnant!', / / message onConfirm, / / rappel d'invoquer avec l'index du bouton enfoncé « Game Over », / / title ['redémarrer', « Exit »] / / buttonLabels) ; + + +### Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 +* Windows + +### Windows Phone 7 et 8 Quirks + +* Il n'y a aucune fonction intégrée au navigateur pour `window.confirm`, mais vous pouvez en lier une en affectant: + + window.confirm = navigator.notification.confirm ; + + +* Les appels à `alert` et `confirm` sont non-bloquants, donc le résultat est seulement disponible de façon asynchrone. + +### Bizarreries de Windows + +* Sur Windows8/8.1, il n'est pas possible d'ajouter plus de trois boutons à MessageDialog instance. + +* Sur Windows Phone 8.1, il n'est pas possible d'établir le dialogue avec plus de deux boutons. + +### Firefox OS Quirks : + +Les deux indigènes bloquant `window.confirm()` et non-bloquante `navigator.notification.confirm()` sont disponibles. + +## navigator.notification.prompt + +Affiche une boîte de dialogue natif qui est plus personnalisable que le navigateur `prompt` fonction. + + Navigator.notification.prompt (message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **message**: message de la boîte de dialogue. *(String)* + +* **promptCallback**: rappel d'invoquer avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans une presse de bouton (0). *(Fonction)* + +* **titre**: titre *(String)* (facultatif, la valeur par défaut de dialogue`Prompt`) + +* **buttonLabels**: tableau de chaînes spécifiant les bouton *(Array)* (facultatif, par défaut, les étiquettes`["OK","Cancel"]`) + +* **defaultText**: zone de texte par défaut entrée valeur ( `String` ) (en option, par défaut : chaîne vide) + +### promptCallback + +Le `promptCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue d'invite. Le `results` objet passé au rappel contient les propriétés suivantes : + +* **buttonIndex**: l'index du bouton activé. *(Nombre)* Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc.. + +* **entrée 1**: le texte entré dans la boîte de dialogue d'invite. *(String)* + +### Exemple + + function onPrompt(results) {alert (« Vous avez sélectionné le numéro du bouton » + results.buttonIndex + « et saisi » + results.input1);} + + Navigator.notification.prompt ('Veuillez saisir votre nom', / / message onPrompt, / / rappel à appeler « Registration », / / title ['Ok', 'Exit'], / / buttonLabels « Jane Doe » / / defaultText) ; + + +### Plates-formes prises en charge + +* Amazon Fire OS +* Android +* Firefox OS +* iOS +* Windows Phone 7 et 8 +* Windows 8 +* Windows + +### Quirks Android + +* Android prend en charge un maximum de trois boutons et ignore plus que cela. + +* Sur Android 3.0 et versions ultérieures, les boutons sont affichés dans l'ordre inverse pour les appareils qui utilisent le thème Holo. + +### Bizarreries de Windows + +* Sous Windows, dialogue d'invite est basé sur html en raison de l'absence de ces api native. + +### Firefox OS Quirks : + +Les deux indigènes bloquant `window.prompt()` et non-bloquante `navigator.notification.prompt()` sont disponibles. + +## navigator.notification.beep + +Le dispositif joue un bip sonore. + + Navigator.notification.Beep(Times) ; + + +* **temps**: le nombre de fois répéter le bip. *(Nombre)* + +### Exemple + + Deux bips ! + Navigator.notification.Beep(2) ; + + +### Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +### Amazon Fire OS Quirks + +* Amazon Fire OS joue la valeur par défaut le **Son de Notification** spécifié sous le panneau **d'affichage des réglages/& Sound** . + +### Quirks Android + +* Android joue la **sonnerie de Notification** spécifié sous le panneau des **réglages/son et affichage** de valeur par défaut. + +### Windows Phone 7 et 8 Quirks + +* S'appuie sur un fichier générique bip de la distribution de Cordova. + +### Bizarreries de paciarelli + +* Paciarelli implémente les bips en lisant un fichier audio via les médias API. + +* Le fichier sonore doit être court, doit se trouver dans un `sounds` sous-répertoire du répertoire racine de l'application et doit être nommé`beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/it/README.md new file mode 100644 index 00000000..8a72905d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/it/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +Questo plugin consente di accedere ad alcuni elementi di interfaccia utente nativa dialogo tramite un oggetto globale `navigator.notification`. + +Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Installazione + + cordova plugin add cordova-plugin-dialogs + + +## Metodi + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +Mostra una finestra di avviso o la finestra di dialogo personalizzata. La maggior parte delle implementazioni di Cordova utilizzano una finestra di dialogo nativa per questa caratteristica, ma alcune piattaforme utilizzano la funzione di `alert` del browser, che è in genere meno personalizzabile. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **message**: messaggio finestra di dialogo. *(String)* + + * **alertCallback**: Callback da richiamare quando viene chiusa la finestra di avviso. *(Funzione)* + + * **title**: titolo di dialogo. *(String)* (Opzionale, default è `Alert`) + + * **buttonName**: nome del pulsante. *(String)* (Opzionale, default è `OK`) + +### Esempio + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + * Windows + +### Windows Phone 7 e 8 stranezze + + * Non non c'è nessun avviso del browser integrato, ma è possibile associare uno come segue per chiamare `alert()` in ambito globale: + + window.alert = navigator.notification.alert; + + + * Entrambi `alert` e `confirm` sono non di blocco chiamate, risultati di cui sono disponibili solo in modo asincrono. + +### Firefox OS Stranezze: + +Nativo di blocco `window.alert()` blocco `navigator.notification.alert()` sono disponibili sia. + +### BlackBerry 10 capricci + +parametro di callback `navigator.notification.alert ('text' callback, 'title' 'text')` viene passato il numero 1. + +## navigator.notification.confirm + +Visualizza una finestra di dialogo conferma personalizzabile. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **message**: messaggio finestra di dialogo. *(String)* + + * **confirmCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)* + + * **titolo**: titolo di dialogo. *(String)* (Opzionale, default è`Confirm`) + + * **buttonLabels**: matrice di stringhe che specificano le etichette dei pulsanti. *(Matrice)* (Opzionale, default è [ `OK,Cancel` ]) + +### confirmCallback + +Il `confirmCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo conferma. + +Il callback accetta l'argomento `buttonIndex` *(numero)*, che è l'indice del pulsante premuto. Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc. + +### Esempio + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + * Windows + +### Windows Phone 7 e 8 stranezze + + * Non non c'è nessuna funzione browser incorporato per `window.confirm` , ma è possibile associare assegnando: + + window.confirm = navigator.notification.confirm; + + + * Chiama al `alert` e `confirm` sono non bloccante, quindi il risultato è disponibile solo in modo asincrono. + +### Stranezze di Windows + + * Su Windows8/8.1 non è possibile aggiungere più di tre pulsanti a MessageDialog istanza. + + * Su Windows Phone 8.1 non è possibile mostrare la finestra di dialogo con più di due pulsanti. + +### Firefox OS Stranezze: + +Nativo di blocco `window.confirm()` blocco `navigator.notification.confirm()` sono disponibili sia. + +## navigator.notification.prompt + +Visualizza una finestra di dialogo nativa che è più personalizzabile di funzione `prompt` del browser. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **message**: messaggio finestra di dialogo. *(String)* + + * **promptCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)* + + * **title**: dialogo titolo *(String)* (opzionale, default è `Prompt`) + + * **buttonLabels**: matrice di stringhe specificando il pulsante etichette *(Array)* (opzionale, default è `["OK", "Cancel"]`) + + * **defaultText**: valore (`String`) di input predefinito textbox (opzionale, Default: empty string) + +### promptCallback + +Il `promptCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo richiesta. `results` oggetto passato al metodo di callback contiene le seguenti proprietà : + + * **buttonIndex**: l'indice del pulsante premuto. *(Numero)* Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc. + + * **input1**: il testo immesso nella finestra di dialogo richiesta. *(String)* + +### Esempio + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### Piattaforme supportate + + * Amazon fuoco OS + * Android + * Firefox OS + * iOS + * Windows Phone 7 e 8 + * Windows 8 + * Windows + +### Stranezze Android + + * Android supporta un massimo di tre pulsanti e ignora di più di quello. + + * Su Android 3.0 e versioni successive, i pulsanti vengono visualizzati in ordine inverso per dispositivi che utilizzano il tema Holo. + +### Stranezze di Windows + + * Su Windows finestra di dialogo richiesta è a causa di mancanza di tali api nativa basata su html. + +### Firefox OS Stranezze: + +Nativo di blocco `window.prompt()` blocco `navigator.notification.prompt()` sono disponibili sia. + +## navigator.notification.beep + +Il dispositivo riproduce un bip sonoro. + + navigator.notification.beep(times); + + + * **times**: il numero di volte per ripetere il segnale acustico. *(Numero)* + +### Esempio + + // Beep twice! + navigator.notification.beep(2); + + +### Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + +### Amazon fuoco OS stranezze + + * Amazon fuoco OS riproduce il **Suono di notifica** specificato sotto il pannello **Impostazioni/Display e il suono** predefinito. + +### Stranezze Android + + * Android giochi default **Notification ringtone** specificato sotto il pannello **impostazioni/audio e Display**. + +### Windows Phone 7 e 8 stranezze + + * Si basa su un file generico bip dalla distribuzione di Cordova. + +### Tizen stranezze + + * Tizen implementa bip di riproduzione di un file audio tramite i media API. + + * Il file beep deve essere breve, deve trovarsi in una sottodirectory di `sounds` della directory principale dell'applicazione e deve essere denominato `beep.wav`.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/it/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/it/index.md new file mode 100644 index 00000000..e8e02c7a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/it/index.md @@ -0,0 +1,273 @@ +<!--- + 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-plugin-dialogs + +Questo plugin consente di accedere ad alcuni elementi di interfaccia utente nativa dialogo tramite un oggetto globale `navigator.notification`. + +Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Installazione + + cordova plugin add cordova-plugin-dialogs + + +## Metodi + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +Mostra una finestra di avviso o la finestra di dialogo personalizzata. La maggior parte delle implementazioni di Cordova utilizzano una finestra di dialogo nativa per questa caratteristica, ma alcune piattaforme utilizzano la funzione di `alert` del browser, che è in genere meno personalizzabile. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + +* **message**: messaggio finestra di dialogo. *(String)* + +* **alertCallback**: Callback da richiamare quando viene chiusa la finestra di avviso. *(Funzione)* + +* **title**: titolo di dialogo. *(String)* (Opzionale, default è `Alert`) + +* **buttonName**: nome del pulsante. *(String)* (Opzionale, default è `OK`) + +### Esempio + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 +* Windows + +### Windows Phone 7 e 8 stranezze + +* Non non c'è nessun avviso del browser integrato, ma è possibile associare uno come segue per chiamare `alert()` in ambito globale: + + window.alert = navigator.notification.alert; + + +* Entrambi `alert` e `confirm` sono non di blocco chiamate, risultati di cui sono disponibili solo in modo asincrono. + +### Firefox OS Stranezze: + +Nativo di blocco `window.alert()` blocco `navigator.notification.alert()` sono disponibili sia. + +### BlackBerry 10 capricci + +parametro di callback `navigator.notification.alert ('text' callback, 'title' 'text')` viene passato il numero 1. + +## navigator.notification.confirm + +Visualizza una finestra di dialogo conferma personalizzabile. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **messaggio**: messaggio finestra di dialogo. *(String)* + +* **confirmCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)* + +* **titolo**: titolo di dialogo. *(String)* (Opzionale, default è`Confirm`) + +* **buttonLabels**: matrice di stringhe che specificano le etichette dei pulsanti. *(Matrice)* (Opzionale, default è [ `OK,Cancel` ]) + +### confirmCallback + +Il `confirmCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo conferma. + +Il callback accetta l'argomento `buttonIndex` *(numero)*, che è l'indice del pulsante premuto. Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc. + +### Esempio + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 +* Windows + +### Windows Phone 7 e 8 stranezze + +* Non non c'è nessuna funzione browser incorporato per `window.confirm` , ma è possibile associare assegnando: + + window.confirm = navigator.notification.confirm; + + +* Chiama al `alert` e `confirm` sono non bloccante, quindi il risultato è disponibile solo in modo asincrono. + +### Stranezze di Windows + +* Su Windows8/8.1 non è possibile aggiungere più di tre pulsanti a MessageDialog istanza. + +* Su Windows Phone 8.1 non è possibile mostrare la finestra di dialogo con più di due pulsanti. + +### Firefox OS Stranezze: + +Nativo di blocco `window.confirm()` blocco `navigator.notification.confirm()` sono disponibili sia. + +## navigator.notification.prompt + +Visualizza una finestra di dialogo nativa che è più personalizzabile di funzione `prompt` del browser. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **message**: messaggio finestra di dialogo. *(String)* + +* **promptCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)* + +* **title**: dialogo titolo *(String)* (opzionale, default è `Prompt`) + +* **buttonLabels**: matrice di stringhe specificando il pulsante etichette *(Array)* (opzionale, default è `["OK", "Cancel"]`) + +* **defaultText**: valore (`String`) di input predefinito textbox (opzionale, Default: empty string) + +### promptCallback + +Il `promptCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo richiesta. `results` oggetto passato al metodo di callback contiene le seguenti proprietà : + +* **buttonIndex**: l'indice del pulsante premuto. *(Numero)* Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc. + +* **input1**: il testo immesso nella finestra di dialogo richiesta. *(String)* + +### Esempio + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### Piattaforme supportate + +* Amazon fuoco OS +* Android +* Firefox OS +* iOS +* Windows Phone 7 e 8 +* Windows 8 +* Windows + +### Stranezze Android + +* Android supporta un massimo di tre pulsanti e ignora di più di quello. + +* Su Android 3.0 e versioni successive, i pulsanti vengono visualizzati in ordine inverso per dispositivi che utilizzano il tema Holo. + +### Stranezze di Windows + +* Su Windows finestra di dialogo richiesta è a causa di mancanza di tali api nativa basata su html. + +### Firefox OS Stranezze: + +Nativo di blocco `window.prompt()` blocco `navigator.notification.prompt()` sono disponibili sia. + +## navigator.notification.beep + +Il dispositivo riproduce un bip sonoro. + + navigator.notification.beep(times); + + +* **times**: il numero di volte per ripetere il segnale acustico. *(Numero)* + +### Esempio + + // Beep twice! + navigator.notification.beep(2); + + +### Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +### Amazon fuoco OS stranezze + +* Amazon fuoco OS riproduce il **Suono di notifica** specificato sotto il pannello **Impostazioni/Display e il suono** predefinito. + +### Stranezze Android + +* Android giochi default **Notification ringtone** specificato sotto il pannello **impostazioni/audio e Display**. + +### Windows Phone 7 e 8 stranezze + +* Si basa su un file generico bip dalla distribuzione di Cordova. + +### Tizen stranezze + +* Tizen implementa bip di riproduzione di un file audio tramite i media API. + +* Il file beep deve essere breve, deve trovarsi in una sottodirectory di `sounds` della directory principale dell'applicazione e deve essere denominato `beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ja/README.md new file mode 100644 index 00000000..0722658b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ja/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +ã“ã®ãƒ—ラグインã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« `navigator.notification` オブジェクトを介ã—ã¦ã„ãã¤ã‹ãƒã‚¤ãƒ†ã‚£ãƒ– ダイアãƒã‚°ã® UI è¦ç´ ã¸ã®ã‚¢ã‚¯ã‚»ã‚¹ã‚’æä¾›ã—ã¾ã™ã€‚ + +オブジェクトã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープ㮠`ナビゲーター` ã«æ·»ä»˜ã€ãれãŒãªã„ã¾ã§ `deviceready` イベントã®å¾Œã€‚ + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## インストール + + cordova plugin add cordova-plugin-dialogs + + +## メソッド + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +カスタムã®è¦å‘Šã¾ãŸã¯ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスãŒè¡¨ç¤ºã•れã¾ã™ã€‚ ã»ã¨ã‚“ã©ã‚³ãƒ«ãƒ‰ãƒ ãƒã‚¤ãƒ†ã‚£ãƒ–] ダイアãƒã‚° ボックスã®ä½¿ç”¨ã“ã®æ©Ÿèƒ½ãŒã„ãã¤ã‹ã®ãƒ—ラットフォームã¯é€šå¸¸å°ã•ã„カスタマイズå¯èƒ½ãªãƒ–ラウザー㮠`è¦å‘Š` 機能を使用ã—ã¾ã™ã€‚ + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **メッセージ**: ダイアãƒã‚° メッセージ。*(æ–‡å—列)* + + * **alertCallback**: è¦å‘Šãƒ€ã‚¤ã‚¢ãƒã‚°ãŒé–‰ã˜ã‚‰ã‚ŒãŸã¨ãã«å‘¼ã³å‡ºã™ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* + + * **タイトル**: ダイアãƒã‚°ã®ã‚¿ã‚¤ãƒˆãƒ«ã€‚*(æ–‡å—列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯`Alert`) + + * **buttonName**: ボタンã®åå‰ã€‚*(æ–‡å—列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯`OK`) + +### 例 + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * Firefox ã® OS + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + * Windows + +### Windows Phone 7 㨠8 ç™– + + * 組ã¿è¾¼ã¿ã®ãƒ–ラウザーè¦å‘ŠãŒãªã„呼ã³å‡ºã—を次ã®ã‚ˆã†ã« 1 ã¤ã‚’ãƒã‚¤ãƒ³ãƒ‰ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ `alert()` ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã€‚ + + window.alert = navigator.notification.alert; + + + * 両方㮠`alert` 㨠`confirm` ã¯éžãƒ–ãƒãƒƒã‚ング呼ã³å‡ºã—ã€çµæžœã¯éžåŒæœŸçš„ã«ã®ã¿åˆ©ç”¨ã§ãã¾ã™ã€‚ + +### Firefox OS 互æ›: + +ãƒã‚¤ãƒ†ã‚£ãƒ– ブãƒãƒƒã‚¯ `window.alert()` ã¨éžãƒ–ãƒãƒƒã‚ング `navigator.notification.alert()` ãŒã‚りã¾ã™ã€‚ + +### ブラックベリー 10 ç™– + +`navigator.notification.alert ('text' コールãƒãƒƒã‚¯ 'title'ã€'text')` コールãƒãƒƒã‚¯ ãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ãƒ¼ã¯æ•° 1 ã«æ¸¡ã•れã¾ã™ã€‚ + +## navigator.notification.confirm + +カスタマイズå¯èƒ½ãªç¢ºèªã®ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **メッセージ**: ダイアãƒã‚° メッセージ。*(æ–‡å—列)* + + * **confirmCallback**: インデックス (1ã€2ã€ã¾ãŸã¯ 3) を押ã•れãŸãƒœã‚¿ãƒ³ã¾ãŸã¯ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスã¯ã€ãƒœã‚¿ãƒ³ã‚’押㙠(0) ãªã—ã«è§£é›‡ã•れãŸã¨ãã«å‘¼ã³å‡ºã™ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* + + * **タイトル**: ダイアãƒã‚°ã®ã‚¿ã‚¤ãƒˆãƒ«ã€‚*(æ–‡å—列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯`Confirm`) + + * **buttonLabels**: ボタンã®ãƒ©ãƒ™ãƒ«ã‚’指定ã™ã‚‹æ–‡å—列ã®é…列。*(é…列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯ [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback` ã¯ã€ã„ãšã‚Œã‹ã®ç¢ºèªãƒ€ã‚¤ã‚¢ãƒã‚° ボックスã§ãƒœã‚¿ãƒ³ã‚’押ã—ãŸã¨ãã«å®Ÿè¡Œã—ã¾ã™ã€‚ + +コールãƒãƒƒã‚¯ã¯ã€å¼•æ•° `buttonIndex` *(番å·ï¼‰* ã¯ã€æŠ¼ã•れãŸãƒœã‚¿ãƒ³ã®ã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ã€‚ インデックスãŒã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ 1 ベースã®ã§ã€å€¤ã¯ `1`ã€`2`ã€`3` ãªã©ã«æ³¨æ„ã—ã¦ãã ã•ã„。 + +### 例 + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * Firefox ã® OS + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + * Windows + +### Windows Phone 7 㨠8 ç™– + + * 組ã¿è¾¼ã¿ãƒ–ãƒ©ã‚¦ã‚¶ãƒ¼ã®æ©Ÿèƒ½ã¯ã‚りã¾ã›ã‚“ `window.confirm` ãŒå‰²ã‚Šå½“ã¦ã‚‹ã“ã¨ã«ã‚ˆã£ã¦ãƒã‚¤ãƒ³ãƒ‰ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã€‚ + + window.confirm = navigator.notification.confirm; + + + * 呼ã³å‡ºã—ã‚’ `alert` 㨠`confirm` ã§ã¯éžãƒ–ãƒãƒƒã‚ングã€çµæžœã¯éžåŒæœŸçš„ã«ã®ã¿ä½¿ç”¨ã§ãã¾ã™ã€‚ + +### Windows ã®ç™– + + * Windows8/8.1 ã® MessageDialog インスタンスを 3 ã¤ä»¥ä¸Šã®ãƒœã‚¿ãƒ³ã‚’è¿½åŠ ã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“。 + + * Windows Phone 8.1 ã« 2 ã¤ä»¥ä¸Šã®ãƒœã‚¿ãƒ³ã‚’æŒã¤ãƒ€ã‚¤ã‚¢ãƒã‚°ã‚’表示ã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“。 + +### Firefox OS 互æ›: + +ãƒã‚¤ãƒ†ã‚£ãƒ– ブãƒãƒƒã‚¯ `window.confirm()` ã¨éžãƒ–ãƒãƒƒã‚ング `navigator.notification.confirm()` ãŒã‚りã¾ã™ã€‚ + +## navigator.notification.prompt + +ブラウザー㮠`プãƒãƒ³ãƒ—ト` 機能より詳細ã«ã‚«ã‚¹ã‚¿ãƒžã‚¤ã‚ºã¯ãƒã‚¤ãƒ†ã‚£ãƒ–ã®ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **メッセージ**: ダイアãƒã‚° メッセージ。*(æ–‡å—列)* + + * **promptCallback**: インデックス (1ã€2ã€ã¾ãŸã¯ 3) を押ã•れãŸãƒœã‚¿ãƒ³ã¾ãŸã¯ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスã¯ã€ãƒœã‚¿ãƒ³ã‚’押㙠(0) ãªã—ã«è§£é›‡ã•れãŸã¨ãã«å‘¼ã³å‡ºã™ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* + + * **title**: タイトル *(String)* (çœç•¥å¯èƒ½ã€æ—¢å®š `プãƒãƒ³ãƒ—ト` ダイアãƒã‚°) + + * **buttonLabels**: ボタンã®ãƒ©ãƒ™ãƒ« *(é…列)* (çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ `["OK"ã€ã€Œã‚ャンセルã€]` を指定ã™ã‚‹æ–‡å—列ã®é…列) + + * **defaultText**: 既定テã‚スト ボックスã®å…¥åЛ値 (`æ–‡å—列`) (çœç•¥å¯èƒ½ã€æ—¢å®š: ç©ºã®æ–‡å—列) + +### promptCallback + +`promptCallback` ã¯ã€ãƒ—ãƒãƒ³ãƒ—ト ダイアãƒã‚° ボックス内ã®ãƒœã‚¿ãƒ³ã®ã„ãšã‚Œã‹ã‚’押ã—ãŸã¨ãã«å®Ÿè¡Œã—ã¾ã™ã€‚コールãƒãƒƒã‚¯ã«æ¸¡ã•れる `results` オブジェクトã«ã¯ã€æ¬¡ã®ãƒ—ãƒãƒ‘ティãŒå«ã¾ã‚Œã¦ã„ã¾ã™ã€‚ + + * **buttonIndex**: 押ã•れãŸãƒœã‚¿ãƒ³ã®ã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ã€‚*(æ•°)*インデックスãŒã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ 1 ベースã®ã§ã€å€¤ã¯ `1`ã€`2`ã€`3` ãªã©ã«æ³¨æ„ã—ã¦ãã ã•ã„。 + + * **input1**: プãƒãƒ³ãƒ—ト ダイアãƒã‚° ボックスã«å…¥åŠ›ã—ãŸãƒ†ã‚スト。*(æ–‡å—列)* + +### 例 + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * Firefox ã® OS + * iOS + * Windows Phone 7 㨠8 + * Windows 8 + * Windows + +### Android ã®ç™– + + * Android ã¯æœ€å¤§ 3 ã¤ã®ãƒœã‚¿ãƒ³ã‚’サãƒãƒ¼ãƒˆã—ã¦ã„ã‚‹ã—ã€ãれ以上無視ã—ã¾ã™ã€‚ + + * アンドãƒã‚¤ãƒ‰ 3.0 ã¨å¾Œã€ãƒ›ãƒã®ãƒ†ãƒ¼ãƒžã‚’使用ã™ã‚‹ãƒ‡ãƒã‚¤ã‚¹ã‚’逆ã®é †åºã§ãƒœã‚¿ãƒ³ãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + +### Windows ã®ç™– + + * Windows プãƒãƒ³ãƒ—ト ダイアãƒã‚°ã¯ html ベースã®ã‚ˆã†ãªãƒã‚¤ãƒ†ã‚£ãƒ– api ã®ä¸è¶³ã®ãŸã‚ã§ã™ã€‚ + +### Firefox OS 互æ›: + +ãƒã‚¤ãƒ†ã‚£ãƒ– ブãƒãƒƒã‚¯ `window.prompt()` ã¨éžãƒ–ãƒãƒƒã‚ング `navigator.notification.prompt()` ãŒã‚りã¾ã™ã€‚ + +## navigator.notification.beep + +デãƒã‚¤ã‚¹ サウンドをビープ音をå†ç”Ÿã—ã¾ã™ã€‚ + + navigator.notification.beep(times); + + + * **times**: ビープ音を繰り返ã™å›žæ•°ã€‚*(æ•°)* + +### 例 + + // Beep twice! + navigator.notification.beep(2); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + +### ã‚¢ãƒžã‚¾ãƒ³ç« OS ç™– + + * ã‚¢ãƒžã‚¾ãƒ³ç« OS デフォルト **è¨å®š/表示 & サウンド** パãƒãƒ«ã®ä¸‹ã«æŒ‡å®šã—㟠**通知音** ã‚’æžœãŸã—ã¦ã„ã¾ã™ã€‚ + +### Android ã®ç™– + + * アンドãƒã‚¤ãƒ‰ デフォルト **通知ç€ä¿¡éŸ³** **è¨å®š/サウンド & ディスプレイ** パãƒãƒ«ã®ä¸‹ã«æŒ‡å®šã‚’æžœãŸã—ã¦ã„ã¾ã™ã€‚ + +### Windows Phone 7 㨠8 ç™– + + * コルドãƒåˆ†å¸ƒã‹ã‚‰ã‚¸ã‚§ãƒãƒªãƒƒã‚¯ ビープ音ファイルã«ä¾å˜ã—ã¾ã™ã€‚ + +### Tizen ã®ç™– + + * Tizen ã¯ã€ãƒ¡ãƒ‡ã‚£ã‚¢ API 経由ã§ã‚ªãƒ¼ãƒ‡ã‚£ã‚ª ファイルをå†ç”Ÿã—ã¦ãƒ“ープ音を実装ã—ã¾ã™ã€‚ + + * ビープ音ファイルçŸã„ã€`sounds` アプリケーションã®ãƒ«ãƒ¼ãƒˆ ディレクトリã®ã‚µãƒ–ディレクトリã§ã‚ã‚‹å¿…è¦ãŒã‚り。ã€`beep.wav` ã¨ã„ã†åå‰ã§ã‚ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/ja/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ja/index.md new file mode 100644 index 00000000..b5308605 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ja/index.md @@ -0,0 +1,273 @@ +<!--- + 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-plugin-dialogs + +ã“ã®ãƒ—ラグインã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« `navigator.notification` オブジェクトを介ã—ã¦ã„ãã¤ã‹ãƒã‚¤ãƒ†ã‚£ãƒ– ダイアãƒã‚°ã® UI è¦ç´ ã¸ã®ã‚¢ã‚¯ã‚»ã‚¹ã‚’æä¾›ã—ã¾ã™ã€‚ + +オブジェクトã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープ㮠`ナビゲーター` ã«æ·»ä»˜ã€ãれãŒãªã„ã¾ã§ `deviceready` イベントã®å¾Œã€‚ + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## インストール + + cordova plugin add cordova-plugin-dialogs + + +## メソッド + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +カスタムã®è¦å‘Šã¾ãŸã¯ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスãŒè¡¨ç¤ºã•れã¾ã™ã€‚ ã»ã¨ã‚“ã©ã‚³ãƒ«ãƒ‰ãƒ ãƒã‚¤ãƒ†ã‚£ãƒ–] ダイアãƒã‚° ボックスã®ä½¿ç”¨ã“ã®æ©Ÿèƒ½ãŒã„ãã¤ã‹ã®ãƒ—ラットフォームã¯é€šå¸¸å°ã•ã„カスタマイズå¯èƒ½ãªãƒ–ラウザー㮠`è¦å‘Š` 機能を使用ã—ã¾ã™ã€‚ + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + +* **メッセージ**: ダイアãƒã‚° メッセージ。*(æ–‡å—列)* + +* **alertCallback**: è¦å‘Šãƒ€ã‚¤ã‚¢ãƒã‚°ãŒé–‰ã˜ã‚‰ã‚ŒãŸã¨ãã«å‘¼ã³å‡ºã™ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* + +* **タイトル**: ダイアãƒã‚°ã®ã‚¿ã‚¤ãƒˆãƒ«ã€‚*(æ–‡å—列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯`Alert`) + +* **buttonName**: ボタンã®åå‰ã€‚*(æ–‡å—列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯`OK`) + +### 例 + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* Firefox ã® OS +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 +* Windows + +### Windows Phone 7 㨠8 ç™– + +* 組ã¿è¾¼ã¿ã®ãƒ–ラウザーè¦å‘ŠãŒãªã„呼ã³å‡ºã—を次ã®ã‚ˆã†ã« 1 ã¤ã‚’ãƒã‚¤ãƒ³ãƒ‰ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ `alert()` ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã€‚ + + window.alert = navigator.notification.alert; + + +* 両方㮠`alert` 㨠`confirm` ã¯éžãƒ–ãƒãƒƒã‚ング呼ã³å‡ºã—ã€çµæžœã¯éžåŒæœŸçš„ã«ã®ã¿åˆ©ç”¨ã§ãã¾ã™ã€‚ + +### Firefox OS 互æ›: + +ãƒã‚¤ãƒ†ã‚£ãƒ– ブãƒãƒƒã‚¯ `window.alert()` ã¨éžãƒ–ãƒãƒƒã‚ング `navigator.notification.alert()` ãŒã‚りã¾ã™ã€‚ + +### ブラックベリー 10 ç™– + +`navigator.notification.alert ('text' コールãƒãƒƒã‚¯ 'title'ã€'text')` コールãƒãƒƒã‚¯ ãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ãƒ¼ã¯æ•° 1 ã«æ¸¡ã•れã¾ã™ã€‚ + +## navigator.notification.confirm + +カスタマイズå¯èƒ½ãªç¢ºèªã®ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **メッセージ**: ダイアãƒã‚° メッセージ。*(æ–‡å—列)* + +* **confirmCallback**: インデックス (1ã€2ã€ã¾ãŸã¯ 3) を押ã•れãŸãƒœã‚¿ãƒ³ã¾ãŸã¯ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスã¯ã€ãƒœã‚¿ãƒ³ã‚’押㙠(0) ãªã—ã«è§£é›‡ã•れãŸã¨ãã«å‘¼ã³å‡ºã™ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* + +* **タイトル**: ダイアãƒã‚°ã®ã‚¿ã‚¤ãƒˆãƒ«ã€‚*(æ–‡å—列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯`Confirm`) + +* **buttonLabels**: ボタンã®ãƒ©ãƒ™ãƒ«ã‚’指定ã™ã‚‹æ–‡å—列ã®é…列。*(é…列)*(çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ã¯ [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback` ã¯ã€ã„ãšã‚Œã‹ã®ç¢ºèªãƒ€ã‚¤ã‚¢ãƒã‚° ボックスã§ãƒœã‚¿ãƒ³ã‚’押ã—ãŸã¨ãã«å®Ÿè¡Œã—ã¾ã™ã€‚ + +コールãƒãƒƒã‚¯ã¯ã€å¼•æ•° `buttonIndex` *(番å·ï¼‰* ã¯ã€æŠ¼ã•れãŸãƒœã‚¿ãƒ³ã®ã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ã€‚ インデックスãŒã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ 1 ベースã®ã§ã€å€¤ã¯ `1`ã€`2`ã€`3` ãªã©ã«æ³¨æ„ã—ã¦ãã ã•ã„。 + +### 例 + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* Firefox ã® OS +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 +* Windows + +### Windows Phone 7 㨠8 ç™– + +* 組ã¿è¾¼ã¿ãƒ–ãƒ©ã‚¦ã‚¶ãƒ¼ã®æ©Ÿèƒ½ã¯ã‚りã¾ã›ã‚“ `window.confirm` ãŒå‰²ã‚Šå½“ã¦ã‚‹ã“ã¨ã«ã‚ˆã£ã¦ãƒã‚¤ãƒ³ãƒ‰ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã€‚ + + window.confirm = navigator.notification.confirm; + + +* 呼ã³å‡ºã—ã‚’ `alert` 㨠`confirm` ã§ã¯éžãƒ–ãƒãƒƒã‚ングã€çµæžœã¯éžåŒæœŸçš„ã«ã®ã¿ä½¿ç”¨ã§ãã¾ã™ã€‚ + +### Windows ã®ç™– + +* Windows8/8.1 ã® MessageDialog インスタンスを 3 ã¤ä»¥ä¸Šã®ãƒœã‚¿ãƒ³ã‚’è¿½åŠ ã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“。 + +* Windows Phone 8.1 ã« 2 ã¤ä»¥ä¸Šã®ãƒœã‚¿ãƒ³ã‚’æŒã¤ãƒ€ã‚¤ã‚¢ãƒã‚°ã‚’表示ã™ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“。 + +### Firefox OS 互æ›: + +ãƒã‚¤ãƒ†ã‚£ãƒ– ブãƒãƒƒã‚¯ `window.confirm()` ã¨éžãƒ–ãƒãƒƒã‚ング `navigator.notification.confirm()` ãŒã‚りã¾ã™ã€‚ + +## navigator.notification.prompt + +ブラウザー㮠`プãƒãƒ³ãƒ—ト` 機能より詳細ã«ã‚«ã‚¹ã‚¿ãƒžã‚¤ã‚ºã¯ãƒã‚¤ãƒ†ã‚£ãƒ–ã®ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **message**: ダイアãƒã‚° メッセージ。*(æ–‡å—列)* + +* **promptCallback**: インデックス (1ã€2ã€ã¾ãŸã¯ 3) を押ã•れãŸãƒœã‚¿ãƒ³ã¾ãŸã¯ãƒ€ã‚¤ã‚¢ãƒã‚° ボックスã¯ã€ãƒœã‚¿ãƒ³ã‚’押㙠(0) ãªã—ã«è§£é›‡ã•れãŸã¨ãã«å‘¼ã³å‡ºã™ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€‚*(機能)* + +* **title**: タイトル *(String)* (çœç•¥å¯èƒ½ã€æ—¢å®š `プãƒãƒ³ãƒ—ト` ダイアãƒã‚°) + +* **buttonLabels**: ボタンã®ãƒ©ãƒ™ãƒ« *(é…列)* (çœç•¥å¯èƒ½ã€æ—¢å®šå€¤ `["OK"ã€ã€Œã‚ャンセルã€]` を指定ã™ã‚‹æ–‡å—列ã®é…列) + +* **defaultText**: 既定テã‚スト ボックスã®å…¥åЛ値 (`æ–‡å—列`) (çœç•¥å¯èƒ½ã€æ—¢å®š: ç©ºã®æ–‡å—列) + +### promptCallback + +`promptCallback` ã¯ã€ãƒ—ãƒãƒ³ãƒ—ト ダイアãƒã‚° ボックス内ã®ãƒœã‚¿ãƒ³ã®ã„ãšã‚Œã‹ã‚’押ã—ãŸã¨ãã«å®Ÿè¡Œã—ã¾ã™ã€‚コールãƒãƒƒã‚¯ã«æ¸¡ã•れる `results` オブジェクトã«ã¯ã€æ¬¡ã®ãƒ—ãƒãƒ‘ティãŒå«ã¾ã‚Œã¦ã„ã¾ã™ã€‚ + +* **buttonIndex**: 押ã•れãŸãƒœã‚¿ãƒ³ã®ã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ã€‚*(æ•°)*インデックスãŒã‚¤ãƒ³ãƒ‡ãƒƒã‚¯ã‚¹ 1 ベースã®ã§ã€å€¤ã¯ `1`ã€`2`ã€`3` ãªã©ã«æ³¨æ„ã—ã¦ãã ã•ã„。 + +* **input1**: プãƒãƒ³ãƒ—ト ダイアãƒã‚° ボックスã«å…¥åŠ›ã—ãŸãƒ†ã‚スト。*(æ–‡å—列)* + +### 例 + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* Firefox ã® OS +* iOS +* Windows Phone 7 㨠8 +* Windows 8 +* Windows + +### Android ã®ç™– + +* Android ã¯æœ€å¤§ 3 ã¤ã®ãƒœã‚¿ãƒ³ã‚’サãƒãƒ¼ãƒˆã—ã¦ã„ã‚‹ã—ã€ãれ以上無視ã—ã¾ã™ã€‚ + +* アンドãƒã‚¤ãƒ‰ 3.0 ã¨å¾Œã€ãƒ›ãƒã®ãƒ†ãƒ¼ãƒžã‚’使用ã™ã‚‹ãƒ‡ãƒã‚¤ã‚¹ã‚’逆ã®é †åºã§ãƒœã‚¿ãƒ³ãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + +### Windows ã®ç™– + +* Windows プãƒãƒ³ãƒ—ト ダイアãƒã‚°ã¯ html ベースã®ã‚ˆã†ãªãƒã‚¤ãƒ†ã‚£ãƒ– api ã®ä¸è¶³ã®ãŸã‚ã§ã™ã€‚ + +### Firefox OS 互æ›: + +ãƒã‚¤ãƒ†ã‚£ãƒ– ブãƒãƒƒã‚¯ `window.prompt()` ã¨éžãƒ–ãƒãƒƒã‚ング `navigator.notification.prompt()` ãŒã‚りã¾ã™ã€‚ + +## navigator.notification.beep + +デãƒã‚¤ã‚¹ サウンドをビープ音をå†ç”Ÿã—ã¾ã™ã€‚ + + navigator.notification.beep(times); + + +* **times**: ビープ音を繰り返ã™å›žæ•°ã€‚*(æ•°)* + +### 例 + + // Beep twice! + navigator.notification.beep(2); + + +### サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +### ã‚¢ãƒžã‚¾ãƒ³ç« OS ç™– + +* ã‚¢ãƒžã‚¾ãƒ³ç« OS デフォルト **è¨å®š/表示 & サウンド** パãƒãƒ«ã®ä¸‹ã«æŒ‡å®šã—㟠**通知音** ã‚’æžœãŸã—ã¦ã„ã¾ã™ã€‚ + +### Android ã®ç™– + +* アンドãƒã‚¤ãƒ‰ デフォルト **通知ç€ä¿¡éŸ³** **è¨å®š/サウンド & ディスプレイ** パãƒãƒ«ã®ä¸‹ã«æŒ‡å®šã‚’æžœãŸã—ã¦ã„ã¾ã™ã€‚ + +### Windows Phone 7 㨠8 ç™– + +* コルドãƒåˆ†å¸ƒã‹ã‚‰ã‚¸ã‚§ãƒãƒªãƒƒã‚¯ ビープ音ファイルã«ä¾å˜ã—ã¾ã™ã€‚ + +### Tizen ã®ç™– + +* Tizen ã¯ã€ãƒ¡ãƒ‡ã‚£ã‚¢ API 経由ã§ã‚ªãƒ¼ãƒ‡ã‚£ã‚ª ファイルをå†ç”Ÿã—ã¦ãƒ“ープ音を実装ã—ã¾ã™ã€‚ + +* ビープ音ファイルçŸã„ã€`sounds` アプリケーションã®ãƒ«ãƒ¼ãƒˆ ディレクトリã®ã‚µãƒ–ディレクトリã§ã‚ã‚‹å¿…è¦ãŒã‚り。ã€`beep.wav` ã¨ã„ã†åå‰ã§ã‚ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ko/README.md new file mode 100644 index 00000000..04532da8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ko/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `navigator.notification` 개체를 통해 몇 가지 기본 대화 ìƒìž UI ìš”ì†Œì— ì•¡ì„¸ìŠ¤í• ìˆ˜ 있습니다. + +개체 `navigator` 글로벌 범위 첨부 아니ì—ìš” 때까지 ì‚¬ìš©í• ìˆ˜ 있는 `deviceready` ì´ë²¤íЏ 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## 설치 + + cordova plugin add cordova-plugin-dialogs + + +## 메서드 + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +ì‚¬ìš©ìž ì§€ì • ê²½ê³ ë˜ëŠ” 대화 ìƒìžë¥¼ ë³´ì—¬ ì¤ë‹ˆë‹¤. ì´ ê¸°ëŠ¥ì— ëŒ€ 한 기본 대화 ìƒìžë¥¼ 사용 하는 ëŒ€ë¶€ë¶„ì˜ ì½”ë¥´ë„ë°” 구현 하지만 ì¼ë¶€ 플랫í¼ì€ ì¼ë°˜ì 으로 ëœ ì‚¬ìš©ìž ì •ì˜í• 수 있는 브ë¼ìš°ì €ì˜ `alert` ê¸°ëŠ¥ì„ ì‚¬ìš© 합니다. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **message**: 대화 메시지. *(문ìžì—´)* + + * **alertCallback**: ì½œë°±ì„ í˜¸ì¶œí• ë•Œ ê²½ê³ ëŒ€í™” 기 ê°. *(기능)* + + * **title**: ì œëª© 대화 ìƒìž. *(문ìžì—´)* (옵션, 기본값:`Alert`) + + * **buttonName**: 단추 ì´ë¦„. *(문ìžì—´)* (옵션, 기본값:`OK`) + +### 예를 들어 + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * Firefox ìš´ì˜ ì²´ì œ + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + * 윈ë„ìš° + +### Windows Phone 7, 8 특수 + + * 아니 내장 브ë¼ìš°ì € ê²½ê³ í•˜ì§€ë§Œ 다ìŒê³¼ ê°™ì´ ì „í™”ë¥¼ ë°”ì¸ë”©í• 수 있습니다 `alert()` ì „ì— ë²”ìœ„ì—서: + + window.alert = navigator.notification.alert; + + + * 둘 다 `alert` 와 `confirm` 는 비차단 호출, ê²°ê³¼ 비ë™ê¸°ì 으로 ì‚¬ìš©í• ìˆ˜ 있습니다. + +### 파ì´ì–´ í스 OS 단ì : + +기본 차단 `window.alert()` ë° ì°¨ë‹¨ ë˜ì§€ ì•Šì€ `navigator.notification.alert()` ì‚¬ìš©í• ìˆ˜ 있습니다. + +### ë¸”ëž™ë² ë¦¬ 10 단ì + +`navigator.notification.alert ('í…스트', 콜백, 'ì œëª©', 'í…스트')` 콜백 매개 변수 1 ë²ˆì„ ì „ë‹¬ ë©ë‹ˆë‹¤. + +## navigator.notification.confirm + +ì‚¬ìš©ìž ì •ì˜ í™•ì¸ ëŒ€í™” ìƒìžê°€ 표시 ë©ë‹ˆë‹¤. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **message**: 대화 메시지. *(문ìžì—´)* + + * **confirmCallback**: ì¸ë±ìФ 버튼 (1, 2 ë˜ëŠ” 3) ë˜ëŠ” 대화 ìƒìž ë²„íŠ¼ì„ ëˆ„ë¥´ë©´ (0) ì—†ì´ ê¸° ê° ë 때 í˜¸ì¶œí• ì½œë°± 합니다. *(기능)* + + * **title**: ì œëª© 대화 ìƒìž. *(문ìžì—´)* (옵션, 기본값:`Confirm`) + + * **buttonLabels**: 단추 ë ˆì´ë¸”ì„ ì§€ì • 하는 문ìžì—´ 배열입니다. *(ë°°ì—´)* (옵션, ê¸°ë³¸ê°’ì€ [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback`는 사용ìžê°€ í™•ì¸ ëŒ€í™” ìƒìžì—서 단추 중 하나를 누를 때 실행 합니다. + +ì½œë°±ì´ ê±¸ë¦½ë‹ˆë‹¤ ì¸ìˆ˜ `buttonIndex` *(번호)를* ëˆ„ë¥´ë©´ëœ ë²„íŠ¼ì˜ ì¸ë±ìŠ¤ìž…ë‹ˆë‹¤. Note ì¸ë±ìФì—서는 ì¸ë±ì‹± 1 시작 ê°’ì€ `1`, `2`, `3`, 등등. + +### 예를 들어 + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * Firefox ìš´ì˜ ì²´ì œ + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + * 윈ë„ìš° + +### Windows Phone 7, 8 특수 + + * ì— ëŒ€ 한 기본 ì œê³µ 브ë¼ìš°ì € 함수가 `window.confirm` , 그러나 í• ë‹¹ 하 ì—¬ ë°”ì¸ë”©í• 수 있습니다: + + window.confirm = navigator.notification.confirm; + + + * 호출 `alert` ë° `confirm` ë˜ë¯€ë¡œ 차단 ë˜ì§€ ì•Šì€ ê²°ê³¼ë§Œ 비ë™ê¸°ì 으로 ì‚¬ìš©í• ìˆ˜ 있습니다. + +### 윈ë„ìš° 특수 + + * Windows8/8.1ì— 3 ê°œ ì´ìƒ 단추 MessageDialog ì¸ìŠ¤í„´ìŠ¤ë¥¼ ì¶”ê°€í• ìˆ˜ëŠ” 없습니다. + + * Windows Phone 8.1ì— ë‘ ê°œ ì´ìƒì˜ 단추와 대화 ìƒìž 표시 수는 없습니다. + +### 파ì´ì–´ í스 OS 단ì : + +기본 차단 `window.confirm()` ë° ì°¨ë‹¨ ë˜ì§€ ì•Šì€ `navigator.notification.confirm()` ì‚¬ìš©í• ìˆ˜ 있습니다. + +## navigator.notification.prompt + +브ë¼ìš°ì €ì˜ `프롬프트` 함수 보다 ë” ë§Žì€ ì‚¬ìš©ìž ì •ì˜ ê¸°ë³¸ 대화 ìƒìžê°€ 표시 ë©ë‹ˆë‹¤. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **message**: 대화 메시지. *(문ìžì—´)* + + * **promptCallback**: ì¸ë±ìФ 버튼 (1, 2 ë˜ëŠ” 3) ë˜ëŠ” 대화 ìƒìž ë²„íŠ¼ì„ ëˆ„ë¥´ë©´ (0) ì—†ì´ ê¸° ê° ë 때 í˜¸ì¶œí• ì½œë°± 합니다. *(기능)* + + * **title**: ì œëª© 대화 ìƒìž. *(문ìžì—´)* (옵션, 기본값:`Prompt`) + + * **buttonLabels**: 버튼 ë ˆì´ë¸” *(ë°°ì—´)* (옵션, 기본값 `["확ì¸", "취소"]ì„` ì§€ì • 하는 문ìžì—´ì˜ ë°°ì—´) + + * **defaultText**: 기본 í…스트 ìƒìžì— ê°’ (`문ìžì—´`) ìž…ë ¥ (옵션, 기본값: 빈 문ìžì—´) + +### promptCallback + +`promptCallback`는 사용ìžê°€ 프롬프트 대화 ìƒìžì—서 단추 중 하나를 누를 때 실행 합니다. ì½œë°±ì— ì „ë‹¬ ëœ `results` 개체ì—는 ë‹¤ìŒ ì†ì„±ì´ í¬í•¨ ë˜ì–´ 있습니다. + + * **buttonIndex**: ëˆŒë ¤ì§„ëœ ë²„íŠ¼ì˜ ì¸ë±ìФ. *(수)* Note ì¸ë±ìФì—서는 ì¸ë±ì‹± 1 시작 ê°’ì€ `1`, `2`, `3`, 등등. + + * **input1**: 프롬프트 대화 ìƒìžì— ìž…ë ¥ 한 í…스트. *(문ìžì—´)* + +### 예를 들어 + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * Firefox ìš´ì˜ ì²´ì œ + * iOS + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + * 윈ë„ìš° + +### 안 드 로ì´ë“œ 단ì + + * 안 드 로ì´ë“œ 최대 3 ê°œì˜ ë‹¨ì¶”ë¥¼ ì§€ì› í•˜ ê³ ê·¸ê²ƒ 보다는 ë” ì´ìƒ 무시 합니다. + + * 안 드 로ì´ë“œ 3.0 ë° ë‚˜ì¤‘ì—, 단추는 홀로 테마를 사용 하는 ìž¥ì¹˜ì— ëŒ€ 한 반대 순서로 표시 ë©ë‹ˆë‹¤. + +### 윈ë„ìš° 특수 + + * 윈ë„ìš°ì—서 프롬프트 대화 ê°™ì€ ë„¤ì´í‹°ë¸Œ apiì˜ ë¶€ì¡±ìœ¼ë¡œ ì¸í•´ html 기반 ì´ë‹¤. + +### 파ì´ì–´ í스 OS 단ì : + +기본 차단 `window.prompt()` ë° ì°¨ë‹¨ ë˜ì§€ ì•Šì€ `navigator.notification.prompt()` ì‚¬ìš©í• ìˆ˜ 있습니다. + +## navigator.notification.beep + +장치는 ê²½ê³ ìŒ ì†Œë¦¬ë¥¼ ìž¬ìƒ í•©ë‹ˆë‹¤. + + navigator.notification.beep(times); + + + * **times**: ê²½ê³ ìŒì„ 반복 하는 횟수. *(수)* + +### 예를 들어 + + // Beep twice! + navigator.notification.beep(2); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + +### 아마존 화재 OS 단ì + + * 아마존 화재 ìš´ì˜ ì²´ì œ 기본 **ì„¤ì •/ë””ìŠ¤í”Œë ˆì´ ë° ì‚¬ìš´ë“œ** 패ë„ì— ì§€ì • ëœ **알림 소리** ìž¬ìƒ ë©ë‹ˆë‹¤. + +### 안 드 로ì´ë“œ 단ì + + * 안 드 로ì´ë“œ 기본 **알림 벨소리** **ì„¤ì •/사운드 ë° ë””ìŠ¤í”Œë ˆì´** 패ë„ì—서 ì§€ì • 합니다. + +### Windows Phone 7, 8 특수 + + * 코르 ë„ìš° ë°” ë¶„í¬ì—서 ì¼ë°˜ ê²½ê³ ìŒ íŒŒì¼ì— ì˜ì¡´í•©ë‹ˆë‹¤. + +### Tizen 특수 + + * Tizenì€ ë¯¸ë””ì–´ API 통해 오디오 파ì¼ì„ ìž¬ìƒ í•˜ ì—¬ ê²½ê³ ìŒì„ 구현 합니다. + + * ê²½ê³ ìŒ íŒŒì¼ ì§§ì€ ë˜ì–´ì•¼ 합니다, ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ë£¨íŠ¸ ë””ë ‰í„°ë¦¬ì˜ `소리` 하위 ë””ë ‰í„°ë¦¬ì— ìœ„ì¹˜ 해야 합니다 ë° `beep.wav`는 명명 ëœ.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/ko/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ko/index.md new file mode 100644 index 00000000..8216d8cf --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ko/index.md @@ -0,0 +1,273 @@ +<!--- + 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-plugin-dialogs + +ì´ í”ŒëŸ¬ê·¸ì¸ ê¸€ë¡œë²Œ `navigator.notification` 개체를 통해 몇 가지 기본 대화 ìƒìž UI ìš”ì†Œì— ì•¡ì„¸ìŠ¤í• ìˆ˜ 있습니다. + +개체 `navigator` 글로벌 범위 첨부 아니ì—ìš” 때까지 ì‚¬ìš©í• ìˆ˜ 있는 `deviceready` ì´ë²¤íЏ 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## 설치 + + cordova plugin add cordova-plugin-dialogs + + +## 메서드 + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +ì‚¬ìš©ìž ì§€ì • ê²½ê³ ë˜ëŠ” 대화 ìƒìžë¥¼ ë³´ì—¬ ì¤ë‹ˆë‹¤. ì´ ê¸°ëŠ¥ì— ëŒ€ 한 기본 대화 ìƒìžë¥¼ 사용 하는 ëŒ€ë¶€ë¶„ì˜ ì½”ë¥´ë„ë°” 구현 하지만 ì¼ë¶€ 플랫í¼ì€ ì¼ë°˜ì 으로 ëœ ì‚¬ìš©ìž ì •ì˜í• 수 있는 브ë¼ìš°ì €ì˜ `alert` ê¸°ëŠ¥ì„ ì‚¬ìš© 합니다. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + +* **message**: 대화 메시지. *(문ìžì—´)* + +* **alertCallback**: ì½œë°±ì„ í˜¸ì¶œí• ë•Œ ê²½ê³ ëŒ€í™” 기 ê°. *(기능)* + +* **title**: ì œëª© 대화 ìƒìž. *(문ìžì—´)* (옵션, 기본값:`Alert`) + +* **buttonName**: 단추 ì´ë¦„. *(문ìžì—´)* (옵션, 기본값:`OK`) + +### 예를 들어 + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* Firefox ìš´ì˜ ì²´ì œ +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 +* 윈ë„ìš° + +### Windows Phone 7, 8 특수 + +* 아니 내장 브ë¼ìš°ì € ê²½ê³ í•˜ì§€ë§Œ 다ìŒê³¼ ê°™ì´ ì „í™”ë¥¼ ë°”ì¸ë”©í• 수 있습니다 `alert()` ì „ì— ë²”ìœ„ì—서: + + window.alert = navigator.notification.alert; + + +* 둘 다 `alert` 와 `confirm` 는 비차단 호출, ê²°ê³¼ 비ë™ê¸°ì 으로 ì‚¬ìš©í• ìˆ˜ 있습니다. + +### 파ì´ì–´ í스 OS 단ì : + +기본 차단 `window.alert()` ë° ì°¨ë‹¨ ë˜ì§€ ì•Šì€ `navigator.notification.alert()` ì‚¬ìš©í• ìˆ˜ 있습니다. + +### ë¸”ëž™ë² ë¦¬ 10 단ì + +`navigator.notification.alert ('í…스트', 콜백, 'ì œëª©', 'í…스트')` 콜백 매개 변수 1 ë²ˆì„ ì „ë‹¬ ë©ë‹ˆë‹¤. + +## navigator.notification.confirm + +ì‚¬ìš©ìž ì •ì˜ í™•ì¸ ëŒ€í™” ìƒìžê°€ 표시 ë©ë‹ˆë‹¤. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **message**: 대화 메시지. *(문ìžì—´)* + +* **confirmCallback**: ì¸ë±ìФ 버튼 (1, 2 ë˜ëŠ” 3) ë˜ëŠ” 대화 ìƒìž ë²„íŠ¼ì„ ëˆ„ë¥´ë©´ (0) ì—†ì´ ê¸° ê° ë 때 í˜¸ì¶œí• ì½œë°± 합니다. *(기능)* + +* **title**: ì œëª© 대화 ìƒìž. *(문ìžì—´)* (옵션, 기본값:`Confirm`) + +* **buttonLabels**: 단추 ë ˆì´ë¸”ì„ ì§€ì • 하는 문ìžì—´ 배열입니다. *(ë°°ì—´)* (옵션, ê¸°ë³¸ê°’ì€ [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback`는 사용ìžê°€ í™•ì¸ ëŒ€í™” ìƒìžì—서 단추 중 하나를 누를 때 실행 합니다. + +ì½œë°±ì´ ê±¸ë¦½ë‹ˆë‹¤ ì¸ìˆ˜ `buttonIndex` *(번호)를* ëˆ„ë¥´ë©´ëœ ë²„íŠ¼ì˜ ì¸ë±ìŠ¤ìž…ë‹ˆë‹¤. Note ì¸ë±ìФì—서는 ì¸ë±ì‹± 1 시작 ê°’ì€ `1`, `2`, `3`, 등등. + +### 예를 들어 + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* Firefox ìš´ì˜ ì²´ì œ +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 +* 윈ë„ìš° + +### Windows Phone 7, 8 특수 + +* ì— ëŒ€ 한 기본 ì œê³µ 브ë¼ìš°ì € 함수가 `window.confirm` , 그러나 í• ë‹¹ 하 ì—¬ ë°”ì¸ë”©í• 수 있습니다: + + window.confirm = navigator.notification.confirm; + + +* 호출 `alert` ë° `confirm` ë˜ë¯€ë¡œ 차단 ë˜ì§€ ì•Šì€ ê²°ê³¼ë§Œ 비ë™ê¸°ì 으로 ì‚¬ìš©í• ìˆ˜ 있습니다. + +### 윈ë„ìš° 특수 + +* Windows8/8.1ì— 3 ê°œ ì´ìƒ 단추 MessageDialog ì¸ìŠ¤í„´ìŠ¤ë¥¼ ì¶”ê°€í• ìˆ˜ëŠ” 없습니다. + +* Windows Phone 8.1ì— ë‘ ê°œ ì´ìƒì˜ 단추와 대화 ìƒìž 표시 수는 없습니다. + +### 파ì´ì–´ í스 OS 단ì : + +기본 차단 `window.confirm()` ë° ì°¨ë‹¨ ë˜ì§€ ì•Šì€ `navigator.notification.confirm()` ì‚¬ìš©í• ìˆ˜ 있습니다. + +## navigator.notification.prompt + +브ë¼ìš°ì €ì˜ `프롬프트` 함수 보다 ë” ë§Žì€ ì‚¬ìš©ìž ì •ì˜ ê¸°ë³¸ 대화 ìƒìžê°€ 표시 ë©ë‹ˆë‹¤. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **message**: 대화 메시지. *(문ìžì—´)* + +* **promptCallback**: ì¸ë±ìФ 버튼 (1, 2 ë˜ëŠ” 3) ë˜ëŠ” 대화 ìƒìž ë²„íŠ¼ì„ ëˆ„ë¥´ë©´ (0) ì—†ì´ ê¸° ê° ë 때 í˜¸ì¶œí• ì½œë°± 합니다. *(기능)* + +* **title**: ì œëª© 대화 ìƒìž. *(문ìžì—´)* (옵션, 기본값:`Prompt`) + +* **buttonLabels**: 버튼 ë ˆì´ë¸” *(ë°°ì—´)* (옵션, 기본값 `["확ì¸", "취소"]ì„` ì§€ì • 하는 문ìžì—´ì˜ ë°°ì—´) + +* **defaultText**: 기본 í…스트 ìƒìžì— ê°’ (`문ìžì—´`) ìž…ë ¥ (옵션, 기본값: 빈 문ìžì—´) + +### promptCallback + +`promptCallback`는 사용ìžê°€ 프롬프트 대화 ìƒìžì—서 단추 중 하나를 누를 때 실행 합니다. ì½œë°±ì— ì „ë‹¬ ëœ `results` 개체ì—는 ë‹¤ìŒ ì†ì„±ì´ í¬í•¨ ë˜ì–´ 있습니다. + +* **buttonIndex**: ëˆŒë ¤ì§„ëœ ë²„íŠ¼ì˜ ì¸ë±ìФ. *(수)* Note ì¸ë±ìФì—서는 ì¸ë±ì‹± 1 시작 ê°’ì€ `1`, `2`, `3`, 등등. + +* **input1**: 프롬프트 대화 ìƒìžì— ìž…ë ¥ 한 í…스트. *(문ìžì—´)* + +### 예를 들어 + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* Firefox ìš´ì˜ ì²´ì œ +* iOS +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 +* 윈ë„ìš° + +### 안 드 로ì´ë“œ 단ì + +* 안 드 로ì´ë“œ 최대 3 ê°œì˜ ë‹¨ì¶”ë¥¼ ì§€ì› í•˜ ê³ ê·¸ê²ƒ 보다는 ë” ì´ìƒ 무시 합니다. + +* 안 드 로ì´ë“œ 3.0 ë° ë‚˜ì¤‘ì—, 단추는 홀로 테마를 사용 하는 ìž¥ì¹˜ì— ëŒ€ 한 반대 순서로 표시 ë©ë‹ˆë‹¤. + +### 윈ë„ìš° 특수 + +* 윈ë„ìš°ì—서 프롬프트 대화 ê°™ì€ ë„¤ì´í‹°ë¸Œ apiì˜ ë¶€ì¡±ìœ¼ë¡œ ì¸í•´ html 기반 ì´ë‹¤. + +### 파ì´ì–´ í스 OS 단ì : + +기본 차단 `window.prompt()` ë° ì°¨ë‹¨ ë˜ì§€ ì•Šì€ `navigator.notification.prompt()` ì‚¬ìš©í• ìˆ˜ 있습니다. + +## navigator.notification.beep + +장치는 ê²½ê³ ìŒ ì†Œë¦¬ë¥¼ ìž¬ìƒ í•©ë‹ˆë‹¤. + + navigator.notification.beep(times); + + +* **times**: ê²½ê³ ìŒì„ 반복 하는 횟수. *(수)* + +### 예를 들어 + + // Beep twice! + navigator.notification.beep(2); + + +### ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +### 아마존 화재 OS 단ì + +* 아마존 화재 ìš´ì˜ ì²´ì œ 기본 **ì„¤ì •/ë””ìŠ¤í”Œë ˆì´ ë° ì‚¬ìš´ë“œ** 패ë„ì— ì§€ì • ëœ **알림 소리** ìž¬ìƒ ë©ë‹ˆë‹¤. + +### 안 드 로ì´ë“œ 단ì + +* 안 드 로ì´ë“œ 기본 **알림 벨소리** **ì„¤ì •/사운드 ë° ë””ìŠ¤í”Œë ˆì´** 패ë„ì—서 ì§€ì • 합니다. + +### Windows Phone 7, 8 특수 + +* 코르 ë„ìš° ë°” ë¶„í¬ì—서 ì¼ë°˜ ê²½ê³ ìŒ íŒŒì¼ì— ì˜ì¡´í•©ë‹ˆë‹¤. + +### Tizen 특수 + +* Tizenì€ ë¯¸ë””ì–´ API 통해 오디오 파ì¼ì„ ìž¬ìƒ í•˜ ì—¬ ê²½ê³ ìŒì„ 구현 합니다. + +* ê²½ê³ ìŒ íŒŒì¼ ì§§ì€ ë˜ì–´ì•¼ 합니다, ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ë£¨íŠ¸ ë””ë ‰í„°ë¦¬ì˜ `소리` 하위 ë””ë ‰í„°ë¦¬ì— ìœ„ì¹˜ 해야 합니다 ë° `beep.wav`는 명명 ëœ. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/pl/README.md new file mode 100644 index 00000000..45fa937c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/pl/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +Ten plugin umożliwia dostÄ™p do niektórych rodzimych okna dialogowego elementy interfejsu użytkownika za poÅ›rednictwem obiektu globalnego `navigator.notification`. + +Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostÄ™pne dopiero po zdarzeniu `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Instalacja + + cordova plugin add cordova-plugin-dialogs + + +## Metody + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +Pokazuje niestandardowe wpisu lub okno dialogowe. WiÄ™kszość implementacji Cordova używać rodzimych okno dialogowe dla tej funkcji, ale niektóre platformy używać przeglÄ…darki `alert` funkcji, która jest zazwyczaj mniej konfigurowalny. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **wiadomość**: komunikat okna dialogowego. *(String)* + + * **alertCallback**: wywoÅ‚anie zwrotne do wywoÅ‚ania, gdy okno dialogowe alert jest oddalona. *(Funkcja)* + + * **tytuÅ‚**: okno tytuÅ‚. *(String)* (Opcjonalna, domyÅ›lnie`Alert`) + + * **buttonName**: Nazwa przycisku. *(String)* (Opcjonalna, domyÅ›lnie`OK`) + +### PrzykÅ‚ad + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + * Windows + +### Windows Phone 7 i 8 dziwactwa + + * Istnieje wpis nie wbudowana przeglÄ…darka, ale można powiÄ…zać w nastÄ™pujÄ…cy sposób na wywoÅ‚anie `alert()` w globalnym zasiÄ™gu: + + window.alert = navigator.notification.alert; + + + * Zarówno `alert` i `confirm` sÄ… bez blokowania połączeÅ„, których wyniki sÄ… tylko dostÄ™pne asynchronicznie. + +### Firefox OS dziwactwa: + +DostÄ™pne sÄ… zarówno rodzimych blokuje `window.alert()` i bez blokowania `navigator.notification.alert()`. + +### Jeżyna 10 dziwactwa + +parametr wywoÅ‚ania zwrotnego `Navigator.Notification.alert ("tekst", wywoÅ‚anie zwrotne, 'tytuÅ‚', 'tekst')` jest przekazywana numer 1. + +## navigator.notification.confirm + +WyÅ›wietla okno dialogowe potwierdzenia konfigurowalny. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **wiadomość**: komunikat okna dialogowego. *(String)* + + * **confirmCallback**: wywoÅ‚anie zwrotne do wywoÅ‚ania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciÅ›nij przycisk (0). *(Funkcja)* + + * **tytuÅ‚**: okno tytuÅ‚. *(String)* (Opcjonalna, domyÅ›lnie`Confirm`) + + * **buttonLabels**: tablica ciÄ…gów, okreÅ›lajÄ…c etykiety przycisków. *(Tablica)* (Opcjonalna, domyÅ›lnie [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback` wykonuje, gdy użytkownik naciÅ›nie klawisz jeden z przycisków w oknie dialogowym potwierdzenia. + +WywoÅ‚anie zwrotne wymaga argumentu `buttonIndex` *(numer)*, który jest indeksem wciÅ›niÄ™ty przycisk. Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, wiÄ™c wartoÅ›ciÄ… jest `1`, `2`, `3` itd. + +### PrzykÅ‚ad + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + * Windows + +### Windows Phone 7 i 8 dziwactwa + + * Istnieje funkcja wbudowana przeglÄ…darka nie `window.confirm` , ale można go powiÄ…zać przypisujÄ…c: + + window.confirm = navigator.notification.confirm; + + + * Wzywa do `alert` i `confirm` sÄ… bez blokowania, wiÄ™c wynik jest tylko dostÄ™pnych asynchronicznie. + +### Windows dziwactwa + + * Na Windows8/8.1 to nie można dodać wiÄ™cej niż trzy przyciski do instancji MessageDialog. + + * Na Windows Phone 8.1 nie jest możliwe wyÅ›wietlić okno dialogowe z wiÄ™cej niż dwoma przyciskami. + +### Firefox OS dziwactwa: + +DostÄ™pne sÄ… zarówno rodzimych blokuje `window.confirm()` i bez blokowania `navigator.notification.confirm()`. + +## navigator.notification.prompt + +WyÅ›wietla okno dialogowe macierzystego, który bardziej niż przeglÄ…darki `prompt` funkcja. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **wiadomość**: komunikat okna dialogowego. *(String)* + + * **promptCallback**: wywoÅ‚anie zwrotne do wywoÅ‚ania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciÅ›nij przycisk (0). *(Funkcja)* + + * **title**: okno tytuÅ‚ *(String)* (opcjonalna, domyÅ›lnie `polecenia`) + + * **buttonLabels**: tablica ciÄ…gów, okreÅ›lajÄ…c przycisk etykiety *(tablica)* (opcjonalna, domyÅ›lnie `["OK", "Anuluj"]`) + + * **defaultText**: domyÅ›lnie pole tekstowe wprowadzania wartoÅ›ci (`String`) (opcjonalna, domyÅ›lnie: pusty ciÄ…g) + +### promptCallback + +`promptCallback` wykonuje, gdy użytkownik naciÅ›nie klawisz jeden z przycisków w oknie dialogowym polecenia. Obiektu `results` przekazane do wywoÅ‚ania zwrotnego zawiera nastÄ™pujÄ…ce wÅ‚aÅ›ciwoÅ›ci: + + * **buttonIndex**: indeks wciÅ›niÄ™ty przycisk. *(Liczba)* Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, wiÄ™c wartoÅ›ciÄ… jest `1`, `2`, `3` itd. + + * **input1**: Tekst wprowadzony w oknie polecenia. *(String)* + +### PrzykÅ‚ad + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * Firefox OS + * iOS + * Windows Phone 7 i 8 + * Windows 8 + * Windows + +### Dziwactwa Androida + + * Android obsÅ‚uguje maksymalnie trzy przyciski i wiÄ™cej niż to ignoruje. + + * Android 3.0 i nowszych przyciski sÄ… wyÅ›wietlane w kolejnoÅ›ci odwrotnej do urzÄ…dzenia, które używajÄ… tematu Holo. + +### Windows dziwactwa + + * W systemie Windows wierzyciel okno jest oparte na jÄ™zyku html, ze wzglÄ™du na brak takich natywnego api. + +### Firefox OS dziwactwa: + +DostÄ™pne sÄ… zarówno rodzimych blokuje `window.prompt()` i bez blokowania `navigator.notification.prompt()`. + +## navigator.notification.beep + +UrzÄ…dzenie odtwarza sygnaÅ‚ ciÄ…gÅ‚y dźwiÄ™k. + + navigator.notification.beep(times); + + + * **times**: liczba powtórzeÅ„ po sygnale. *(Liczba)* + +### PrzykÅ‚ad + + // Beep twice! + navigator.notification.beep(2); + + +### ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + +### Amazon ogieÅ„ OS dziwactwa + + * Amazon ogieÅ„ OS gra domyÅ›lny **DźwiÄ™k powiadomienia** okreÅ›lone w panelu **ekranu/ustawienia i dźwiÄ™k**. + +### Dziwactwa Androida + + * Android gra domyÅ›lnie **dzwonek powiadomienia** okreÅ›lone w panelu **ustawieÅ„/dźwiÄ™k i wyÅ›wietlacz**. + +### Windows Phone 7 i 8 dziwactwa + + * Opiera siÄ™ na pliku rodzajowego sygnaÅ‚ z rozkÅ‚adu Cordova. + +### Dziwactwa Tizen + + * Tizen implementuje dźwiÄ™ków przez odtwarzania pliku audio za poÅ›rednictwem mediów API. + + * Plik dźwiÄ™kowy muszÄ… być krótkie, musi znajdować siÄ™ w podkatalogu `dźwiÄ™ki` w katalogu głównym aplikacji i musi być o nazwie `beep.wav`.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/pl/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/pl/index.md new file mode 100644 index 00000000..462d5ac2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/pl/index.md @@ -0,0 +1,273 @@ +<!--- + 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-plugin-dialogs + +Ten plugin umożliwia dostÄ™p do niektórych rodzimych okna dialogowego elementy interfejsu użytkownika za poÅ›rednictwem obiektu globalnego `navigator.notification`. + +Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostÄ™pne dopiero po zdarzeniu `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## Instalacja + + cordova plugin add cordova-plugin-dialogs + + +## Metody + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +Pokazuje niestandardowe wpisu lub okno dialogowe. WiÄ™kszość implementacji Cordova używać rodzimych okno dialogowe dla tej funkcji, ale niektóre platformy używać przeglÄ…darki `alert` funkcji, która jest zazwyczaj mniej konfigurowalny. + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + +* **wiadomość**: komunikat okna dialogowego. *(String)* + +* **alertCallback**: wywoÅ‚anie zwrotne do wywoÅ‚ania, gdy okno dialogowe alert jest oddalona. *(Funkcja)* + +* **tytuÅ‚**: okno tytuÅ‚. *(String)* (Opcjonalna, domyÅ›lnie`Alert`) + +* **buttonName**: Nazwa przycisku. *(String)* (Opcjonalna, domyÅ›lnie`OK`) + +### PrzykÅ‚ad + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 +* Windows + +### Windows Phone 7 i 8 dziwactwa + +* Istnieje wpis nie wbudowana przeglÄ…darka, ale można powiÄ…zać w nastÄ™pujÄ…cy sposób na wywoÅ‚anie `alert()` w globalnym zasiÄ™gu: + + window.alert = navigator.notification.alert; + + +* Zarówno `alert` i `confirm` sÄ… bez blokowania połączeÅ„, których wyniki sÄ… tylko dostÄ™pne asynchronicznie. + +### Firefox OS dziwactwa: + +DostÄ™pne sÄ… zarówno rodzimych blokuje `window.alert()` i bez blokowania `navigator.notification.alert()`. + +### Jeżyna 10 dziwactwa + +parametr wywoÅ‚ania zwrotnego `Navigator.Notification.alert ("tekst", wywoÅ‚anie zwrotne, 'tytuÅ‚', 'tekst')` jest przekazywana numer 1. + +## navigator.notification.confirm + +WyÅ›wietla okno dialogowe potwierdzenia konfigurowalny. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **wiadomość**: komunikat okna dialogowego. *(String)* + +* **confirmCallback**: wywoÅ‚anie zwrotne do wywoÅ‚ania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciÅ›nij przycisk (0). *(Funkcja)* + +* **tytuÅ‚**: okno tytuÅ‚. *(String)* (Opcjonalna, domyÅ›lnie`Confirm`) + +* **buttonLabels**: tablica ciÄ…gów, okreÅ›lajÄ…c etykiety przycisków. *(Tablica)* (Opcjonalna, domyÅ›lnie [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback` wykonuje, gdy użytkownik naciÅ›nie klawisz jeden z przycisków w oknie dialogowym potwierdzenia. + +WywoÅ‚anie zwrotne wymaga argumentu `buttonIndex` *(numer)*, który jest indeksem wciÅ›niÄ™ty przycisk. Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, wiÄ™c wartoÅ›ciÄ… jest `1`, `2`, `3` itd. + +### PrzykÅ‚ad + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 +* Windows + +### Windows Phone 7 i 8 dziwactwa + +* Istnieje funkcja wbudowana przeglÄ…darka nie `window.confirm` , ale można go powiÄ…zać przypisujÄ…c: + + window.confirm = navigator.notification.confirm; + + +* Wzywa do `alert` i `confirm` sÄ… bez blokowania, wiÄ™c wynik jest tylko dostÄ™pnych asynchronicznie. + +### Windows dziwactwa + +* Na Windows8/8.1 to nie można dodać wiÄ™cej niż trzy przyciski do instancji MessageDialog. + +* Na Windows Phone 8.1 nie jest możliwe wyÅ›wietlić okno dialogowe z wiÄ™cej niż dwoma przyciskami. + +### Firefox OS dziwactwa: + +DostÄ™pne sÄ… zarówno rodzimych blokuje `window.confirm()` i bez blokowania `navigator.notification.confirm()`. + +## navigator.notification.prompt + +WyÅ›wietla okno dialogowe macierzystego, który bardziej niż przeglÄ…darki `prompt` funkcja. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **message**: komunikat okna dialogowego. *(String)* + +* **promptCallback**: wywoÅ‚anie zwrotne do wywoÅ‚ania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciÅ›nij przycisk (0). *(Funkcja)* + +* **title**: okno tytuÅ‚ *(String)* (opcjonalna, domyÅ›lnie `polecenia`) + +* **buttonLabels**: tablica ciÄ…gów, okreÅ›lajÄ…c przycisk etykiety *(tablica)* (opcjonalna, domyÅ›lnie `["OK", "Anuluj"]`) + +* **defaultText**: domyÅ›lnie pole tekstowe wprowadzania wartoÅ›ci (`String`) (opcjonalna, domyÅ›lnie: pusty ciÄ…g) + +### promptCallback + +`promptCallback` wykonuje, gdy użytkownik naciÅ›nie klawisz jeden z przycisków w oknie dialogowym polecenia. Obiektu `results` przekazane do wywoÅ‚ania zwrotnego zawiera nastÄ™pujÄ…ce wÅ‚aÅ›ciwoÅ›ci: + +* **buttonIndex**: indeks wciÅ›niÄ™ty przycisk. *(Liczba)* Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, wiÄ™c wartoÅ›ciÄ… jest `1`, `2`, `3` itd. + +* **input1**: Tekst wprowadzony w oknie polecenia. *(String)* + +### PrzykÅ‚ad + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* Firefox OS +* iOS +* Windows Phone 7 i 8 +* Windows 8 +* Windows + +### Dziwactwa Androida + +* Android obsÅ‚uguje maksymalnie trzy przyciski i wiÄ™cej niż to ignoruje. + +* Android 3.0 i nowszych przyciski sÄ… wyÅ›wietlane w kolejnoÅ›ci odwrotnej do urzÄ…dzenia, które używajÄ… tematu Holo. + +### Windows dziwactwa + +* W systemie Windows wierzyciel okno jest oparte na jÄ™zyku html, ze wzglÄ™du na brak takich natywnego api. + +### Firefox OS dziwactwa: + +DostÄ™pne sÄ… zarówno rodzimych blokuje `window.prompt()` i bez blokowania `navigator.notification.prompt()`. + +## navigator.notification.beep + +UrzÄ…dzenie odtwarza sygnaÅ‚ ciÄ…gÅ‚y dźwiÄ™k. + + navigator.notification.beep(times); + + +* **times**: liczba powtórzeÅ„ po sygnale. *(Liczba)* + +### PrzykÅ‚ad + + // Beep twice! + navigator.notification.beep(2); + + +### ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +### Amazon ogieÅ„ OS dziwactwa + +* Amazon ogieÅ„ OS gra domyÅ›lny **DźwiÄ™k powiadomienia** okreÅ›lone w panelu **ekranu/ustawienia i dźwiÄ™k**. + +### Dziwactwa Androida + +* Android gra domyÅ›lnie **dzwonek powiadomienia** okreÅ›lone w panelu **ustawieÅ„/dźwiÄ™k i wyÅ›wietlacz**. + +### Windows Phone 7 i 8 dziwactwa + +* Opiera siÄ™ na pliku rodzajowego sygnaÅ‚ z rozkÅ‚adu Cordova. + +### Dziwactwa Tizen + +* Tizen implementuje dźwiÄ™ków przez odtwarzania pliku audio za poÅ›rednictwem mediów API. + +* Plik dźwiÄ™kowy muszÄ… być krótkie, musi znajdować siÄ™ w podkatalogu `dźwiÄ™ki` w katalogu głównym aplikacji i musi być o nazwie `beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/ru/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ru/index.md new file mode 100644 index 00000000..49474ead --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/ru/index.md @@ -0,0 +1,247 @@ +<!--- + 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-plugin-dialogs + +Ðтот плагин обеÑпечивает доÑтуп к некоторым Ñлементам ÑобÑтвенного диалогового окна пользовательÑкого интерфейÑа. + +## УÑтановка + + cordova plugin add cordova-plugin-dialogs + + +## Методы + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +Показывает окно пользовательÑкие Ð¾Ð¿Ð¾Ð²ÐµÑ‰ÐµÐ½Ð¸Ñ Ð¸Ð»Ð¸ диалоговое окно. БольшинÑтво реализаций Cordova иÑпользовать диалоговое окно родной Ð´Ð»Ñ Ñтой функции, но некоторые платформы браузера `alert` функциÑ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ ÐºÐ°Ðº правило менее наÑтраиваетÑÑ. + + Navigator.Notification.Alert (Ñообщение, alertCallback, [название], [buttonName]) + + +* **Ñообщение**: Ñообщение диалога. *(Строка)* + +* **alertCallback**: обратного вызова Ð´Ð»Ñ Ð²Ñ‹Ð·Ð¾Ð²Ð°, когда закрываетÑÑ Ð´Ð¸Ð°Ð»Ð¾Ð³Ð¾Ð²Ð¾Ðµ окно оповещениÑ. *(ФункциÑ)* + +* **название**: диалоговое окно название. *(Строка)* (Опционально, по умолчанию`Alert`) + +* **buttonName**: Ð¸Ð¼Ñ ÐºÐ½Ð¾Ð¿ÐºÐ¸. *(Строка)* (Опционально, по умолчанию`OK`) + +### Пример + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### ОÑобенноÑти Windows Phone 7 и 8 + +* СущеÑтвует предупреждение не вÑтроенный браузер, но можно привÑзать один Ñледующим позвонить `alert()` в глобальной облаÑти дейÑтвиÑ: + + window.alert = navigator.notification.alert; + + +* Оба `alert` и `confirm` ÑвлÑÑŽÑ‚ÑÑ Ð½Ðµ блокировка звонков, результаты которых доÑтупны только аÑинхронно. + +### Firefox OS причуды: + +Как родной блокировка `window.alert()` и неблокирующий `navigator.notification.alert()` доÑтупны. + +## navigator.notification.confirm + +Отображает диалоговое окно ÐаÑтраиваемый подтверждениÑ. + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **Ñообщение**: Ñообщение диалога. *(Строка)* + +* **confirmCallback**: обратного вызова Ñ Ð¸Ð½Ð´ÐµÐºÑом кнопка нажата (1, 2 или 3) или когда диалоговое окно закрываетÑÑ Ð±ÐµÐ· Ð½Ð°Ð¶Ð°Ñ‚Ð¸Ñ ÐºÐ½Ð¾Ð¿ÐºÐ¸ (0). *(ФункциÑ)* + +* **название**: диалоговое окно название. *(Строка)* (Опционально, по умолчанию`Confirm`) + +* **buttonLabels**: маÑÑив Ñтрок, указав Ð½Ð°Ð·Ð²Ð°Ð½Ð¸Ñ ÐºÐ½Ð¾Ð¿Ð¾Ðº. *(МаÑÑив)* (Ðе обÑзательно, по умолчанию [ `OK,Cancel` ]) + +### confirmCallback + +`confirmCallback`ВыполнÑетÑÑ, когда пользователь нажимает одну из кнопок в диалоговом окне подтверждениÑ. + +Ðргументом функции обратного вызова `buttonIndex` *(номер)*, который ÑвлÑетÑÑ Ð¸Ð½Ð´ÐµÐºÑ Ð½Ð°Ð¶Ð°Ñ‚Ð¾Ð¹ кнопки. Обратите внимание, что Ð¸Ð½Ð´ÐµÐºÑ Ð¸Ñпользует единицы индекÑации, поÑтому значение `1` , `2` , `3` , и Ñ‚.д. + +### Пример + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### ОÑобенноÑти Windows Phone 7 и 8 + +* Ðет вÑтроенного браузера Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð´Ð»Ñ `window.confirm` , но его можно привÑзать путем приÑвоениÑ: + + window.confirm = navigator.notification.confirm; + + +* Вызовы `alert` и `confirm` ÑвлÑÑŽÑ‚ÑÑ Ð½Ðµ блокируетÑÑ, поÑтому результат доÑтупен только аÑинхронно. + +### Firefox OS причуды: + +Как родной блокировка `window.confirm()` и неблокирующий `navigator.notification.confirm()` доÑтупны. + +## navigator.notification.prompt + +Отображает родной диалоговое окно более наÑтраиваемый, чем в браузере `prompt` функции. + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **Ñообщение**: Ñообщение диалога. *(Строка)* + +* **promptCallback**: обратного вызова Ñ Ð¸Ð½Ð´ÐµÐºÑом кнопка нажата (1, 2 или 3) или когда диалоговое окно закрываетÑÑ Ð±ÐµÐ· Ð½Ð°Ð¶Ð°Ñ‚Ð¸Ñ ÐºÐ½Ð¾Ð¿ÐºÐ¸ (0). *(ФункциÑ)* + +* **название**: диалоговое окно название *(String)* (опционально, по умолчанию`Prompt`) + +* **buttonLabels**: маÑÑив Ñтрок, указав кнопку Ñтикетки *(маÑÑив)* (опционально, по умолчанию`["OK","Cancel"]`) + +* **defaultText**: по умолчанию textbox входное значение ( `String` ) (опционально, по умолчанию: пуÑÑ‚Ð°Ñ Ñтрока) + +### promptCallback + +`promptCallback`ВыполнÑетÑÑ, когда пользователь нажимает одну из кнопок в диалоговом окне приглашениÑ. `results`Объект, переданный в метод обратного вызова Ñодержит Ñледующие ÑвойÑтва: + +* **buttonIndex**: Ð¸Ð½Ð´ÐµÐºÑ Ð½Ð°Ð¶Ð°Ñ‚Ð¾Ð¹ кнопки. *(ЧиÑло)* Обратите внимание, что Ð¸Ð½Ð´ÐµÐºÑ Ð¸Ñпользует единицы индекÑации, поÑтому значение `1` , `2` , `3` , и Ñ‚.д. + +* **INPUT1**: текÑÑ‚, введенный в диалоговом окне приглашениÑ. *(Строка)* + +### Пример + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### Поддерживаемые платформы + +* Amazon Fire OS +* Android +* Firefox OS +* iOS +* Windows Phone 7 и 8 + +### ОÑобенноÑти Android + +* Android поддерживает макÑимум из трех кнопок и игнорирует больше, чем Ñто. + +* Ðа Android 3.0 и более поздних верÑиÑÑ… кнопки отображаютÑÑ Ð² обратном порÑдке Ð´Ð»Ñ ÑƒÑтройÑтв, которые иÑпользуют тему холо. + +### Firefox OS причуды: + +Как родной блокировка `window.prompt()` и неблокирующий `navigator.notification.prompt()` доÑтупны. + +## navigator.notification.beep + +УÑтройÑтво воÑпроизводит звуковой Ñигнал звук. + + navigator.notification.beep(times); + + +* **раз**: количеÑтво раз, чтобы повторить Ñигнал. *(ЧиÑло)* + +### Пример + + // Beep twice! + navigator.notification.beep(2); + + +### Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +### ОÑобенноÑти Amazon Fire OS + +* Amazon Fire OS играет по умолчанию **Звук уведомлениÑ** , указанного на панели **параметров/диÑплей и звук** . + +### ОÑобенноÑти Android + +* Android играет по умолчанию **ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ Ñ€Ð¸Ð½Ð³Ñ‚Ð¾Ð½** указанных в панели **наÑтройки/звук и диÑплей** . + +### ОÑобенноÑти Windows Phone 7 и 8 + +* ОпираетÑÑ Ð½Ð° общий звуковой файл из диÑтрибутива Кордова. + +### ОÑобенноÑти Tizen + +* Tizen реализует гудков, воÑпроизведении аудиофайла через СМИ API. + +* Звуковой файл должен быть коротким, должен быть раÑположен в `sounds` подкаталог корневого каталога Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð¸ должны быть названы`beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/zh/README.md new file mode 100644 index 00000000..c8c26c3d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/zh/README.md @@ -0,0 +1,275 @@ +<!-- +# license: 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-plugin-dialogs + +[](https://travis-ci.org/apache/cordova-plugin-dialogs) + +é€™å€‹å¤–æŽ›ç¨‹å¼æä¾›å°ä¸€äº›æœ¬æ©Ÿå°è©±æ–¹å¡Šä½¿ç”¨è€…介é¢å…ƒç´ ,通éŽå…¨çƒ `navigator.notification` 物件的訪å•。 + +é›–ç„¶è©²ç‰©ä»¶é™„åŠ åˆ°å…¨çƒç¯„åœå…§ `導航器`,它ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-dialogs + + +## 方法 + + * `navigator.notification.alert` + * `navigator.notification.confirm` + * `navigator.notification.prompt` + * `navigator.notification.beep` + +## navigator.notification.alert + +顯示一個自訂的è¦å ±æˆ–å°è©±æ–¹å¡Šæ¡†ã€‚ 大多數的科爾多瓦實ç¾ä½¿ç”¨æœ¬æ©Ÿçš„å°è©±æ–¹å¡Šç‚ºæ¤åŠŸèƒ½ï¼Œä½†æŸäº›å¹³è‡ºä¸Šä½¿ç”¨ç€è¦½å™¨çš„ `alert` 功能,這是通常ä¸é‚£éº¼å¯è‡ªè¨‚。 + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + + * **message**: 消æ¯å°è©±æ–¹å¡Šã€‚*(String)* + + * **alertCallback**: ç•¶è¦å ±å°è©±æ–¹å¡Šçš„被解雇時è¦èª¿ç”¨çš„回檔。*(函數)* + + * **title**: 標題å°è©±æ–¹å¡Šã€‚*(String)*(å¯é¸ï¼Œé è¨å€¼ç‚º`Alert`) + + * **buttonName**: 按鈕å稱。*(å—串)*(å¯é¸ï¼Œé è¨å€¼ç‚º`OK`) + +### 示例 + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + * Windows + +### Windows Phone 7 å’Œ 8 怪癖 + + * 有沒有內置ç€è¦½å™¨è¦å ±ï¼Œä½†ä½ å¯ä»¥ç¶å®šä¸€å€‹ï¼Œå¦‚下所示調用 `alert()` 在全çƒç¯„åœå…§ï¼š + + window.alert = navigator.notification.alert; + + + * 兩個 `alert` å’Œ `confirm` çš„éžé˜»å¡žçš„調用,其ä¸çš„çµæžœæ‰æ˜¯å¯ç”¨çš„éžåŒæ¥ã€‚ + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±æ€ªç™–: + +æœ¬æ©Ÿé˜»æ¢ `window.alert()` å’Œéžé˜»å¡žçš„ `navigator.notification.alert()` 都å¯ã€‚ + +### 黑莓 10 怪癖 + +`navigator.notification.alert ('message'〠confirmCallback〠'title'〠'buttonLabels')` å›žæª”åƒæ•¸è¢«å‚³éžçš„æ•¸ä½ 1。 + +## navigator.notification.confirm + +顯示一個å¯è‡ªè¨‚的確èªå°è©±æ–¹å¡Šã€‚ + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + + * **message**: 消æ¯å°è©±æ–¹å¡Šã€‚*(String)* + + * **confirmCallback**: è¦ç”¨ç´¢å¼• (1〠2 或 3) 按下的按鈕,或者在沒有按下按鈕 (0) é§å›žäº†å°è©±æ–¹å¡Šä¸æ™‚調用的回檔。*(函數)* + + * **title**: 標題å°è©±æ–¹å¡Šã€‚*(å—串)*(å¯é¸ï¼Œé è¨å€¼ç‚º`Confirm`) + + * **buttonLabels**: 指定按鈕標籤的å—串陣列。*(陣列)*(å¯é¸ï¼Œé è¨å€¼ç‚º [ `OK,Cancel` ]) + +### confirmCallback + +當使用者按下確èªå°è©±æ–¹å¡Šä¸çš„æŒ‰éˆ•之一時,將執行 `confirmCallback`。 + +回檔需è¦åƒæ•¸ `buttonIndex` *(編號)*ï¼Œå³æŒ‰ä¸‹çš„æŒ‰éˆ•的索引。 請注æ„ç´¢å¼•ä½¿ç”¨ä¸€å€‹åŸºæ–¼ç´¢å¼•ï¼Œå› æ¤å€¼ `1`〠`2`〠`3` ç‰ã€‚ + +### 示例 + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + * Windows + +### Windows Phone 7 å’Œ 8 怪癖 + + * 有沒有內置的ç€è¦½å™¨åŠŸèƒ½çš„ `window.confirm` ï¼Œä½†ä½ å¯ä»¥å°‡å®ƒç¶å®šé€šéŽåˆ†é…: + + window.confirm = navigator.notification.confirm; + + + * 調用到 `alert` å’Œ `confirm` çš„éžé˜»å¡žï¼Œæ‰€ä»¥çµæžœå°±æ˜¯åªå¯ç”¨ä»¥éžåŒæ¥æ–¹å¼ã€‚ + +### Windows 的怪癖 + + * 在 Windows8/8.1 它是ä¸å¯èƒ½å°‡è¶…éŽä¸‰å€‹æŒ‰éˆ•æ·»åŠ åˆ° MessageDialog 實例。 + + * 在 Windows Phone 8.1 它是ä¸å¯èƒ½é¡¯ç¤ºæœ‰è¶…éŽå…©å€‹æŒ‰éˆ•çš„å°è©±æ–¹å¡Šã€‚ + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±æ€ªç™–: + +æœ¬æ©Ÿé˜»æ¢ `window.confirm()` å’Œéžé˜»å¡žçš„ `navigator.notification.confirm()` 都å¯ã€‚ + +## navigator.notification.prompt + +顯示本機的å°è©±æ–¹å¡Šï¼Œæ˜¯å¯å®šåˆ¶çš„æ¯”ç€è¦½å™¨çš„ `prompt` 功能。 + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + + * **message**: 消æ¯å°è©±æ–¹å¡Šã€‚*(String)* + + * **promptCallback**: è¦ç”¨æŒ‡æ•¸ (1〠2 或 3) 按下的按鈕或å°è©±æ–¹å¡Šä¸è§£é›‡ç„¡ (0) 按下一個按鈕時調用的回檔。*(函數)* + + * **title**: 標題å°è©±æ–¹å¡Šã€‚*(String)*(å¯é¸ï¼Œé è¨å€¼ç‚º`Alert`) + + * **buttonLabels**: 指定按鈕標籤 (å¯é¸ï¼Œé è¨å€¼ç‚º `["OK","Cancel"]` *(陣列)* çš„å—串陣列) + + * **defaultText**: é è¨æ–‡å—方塊ä¸è¼¸å…¥å€¼ (`å—串`) (å¯é¸ï¼Œé è¨å€¼ï¼š 空å—串) + +### promptCallback + +當使用者按下其ä¸ä¸€å€‹æç¤ºå°è©±æ–¹å¡Šä¸çš„æŒ‰éˆ•時,將執行 `promptCallback`。傳éžçµ¦å›žæª”çš„ `results` 物件包å«ä»¥ä¸‹å±¬æ€§ï¼š + + * **buttonIndex**: 按下的按鈕的索引。*(數)*請注æ„ç´¢å¼•ä½¿ç”¨ä¸€å€‹åŸºæ–¼ç´¢å¼•ï¼Œå› æ¤å€¼ `1`〠`2`〠`3` ç‰ã€‚ + + * **input1**: 在æç¤ºå°è©±æ–¹å¡Šä¸è¼¸å…¥çš„æ–‡æœ¬ã€‚*(å—串)* + +### 示例 + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + * iOS + * Windows Phone 7 å’Œ 8 + * Windows 8 + * Windows + +### Android 的怪癖 + + * Android æ”¯æ´æœ€å¤šçš„三個按鈕,並忽略任何更多。 + + * 在 Android 3.0 åŠæ›´é«˜ç‰ˆæœ¬ï¼Œä½¿ç”¨å…¨æ¯ä¸»é¡Œçš„è¨å‚™ä»¥ç›¸åçš„é †åºé¡¯ç¤ºæŒ‰éˆ•。 + +### Windows 的怪癖 + + * 在 Windows 上æç¤ºå°è©±æ–¹å¡Šæ˜¯åŸºæ–¼ html 的缺ä¹é€™ç¨®æœ¬æ©Ÿ api。 + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±æ€ªç™–: + +æœ¬æ©Ÿé˜»æ¢ `window.prompt()` å’Œéžé˜»å¡žçš„ `navigator.notification.prompt()` 都å¯ã€‚ + +## navigator.notification.beep + +該è¨å‚™æ’放æç¤ºéŸ³çš„è²éŸ³ã€‚ + + navigator.notification.beep(times); + + + * **beep**: 次數é‡è¤‡åœ¨å—¶å—¶è²ã€‚*(數)* + +### 示例 + + // Beep twice! + navigator.notification.beep(2); + + +### 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + +### 亞馬éœç« OS 怪癖 + + * 亞馬éœç« OS æ’æ”¾é è¨ **è¨ç½®/顯示和è²éŸ³** æ¿ä¸‹æŒ‡å®šçš„ **通知è²éŸ³**。 + +### Android 的怪癖 + + * 安å“ç³»çµ±æ’æ”¾é è¨ **通知鈴è²** **è¨ç½®/è²éŸ³å’Œé¡¯ç¤º** 颿¿ä¸‹æŒ‡å®šã€‚ + +### Windows Phone 7 å’Œ 8 怪癖 + + * ä¾è³´äºŽæ³›åž‹èœ‚鳴音檔從科爾多瓦分佈。 + +### Tizen 怪癖 + + * Tizen é€šéŽæ’放音訊檔通éŽåª’é«” API 實ç¾çš„蜂鳴è²ã€‚ + + * èœ‚é³´éŸ³æª”å¿…é ˆå¾ˆçŸï¼Œå¿…é ˆä½æ–¼æ‡‰ç”¨ç¨‹å¼çš„æ ¹ç›®éŒ„ä¸ï¼Œä¸€å€‹ `è²éŸ³` åç›®éŒ„å’Œå¿…é ˆå°‡å‘½å為 `beep.wav`.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/doc/zh/index.md b/StoneIsland/plugins/cordova-plugin-dialogs/doc/zh/index.md new file mode 100644 index 00000000..b47fc5f9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/doc/zh/index.md @@ -0,0 +1,273 @@ +<!--- + 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-plugin-dialogs + +é€™å€‹å¤–æŽ›ç¨‹å¼æä¾›å°ä¸€äº›æœ¬æ©Ÿå°è©±æ–¹å¡Šä½¿ç”¨è€…介é¢å…ƒç´ ,通éŽå…¨çƒ `navigator.notification` 物件的訪å•。 + +é›–ç„¶è©²ç‰©ä»¶é™„åŠ åˆ°å…¨çƒç¯„åœå…§ `導航器`,它ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log(navigator.notification); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-dialogs + + +## 方法 + +* `navigator.notification.alert` +* `navigator.notification.confirm` +* `navigator.notification.prompt` +* `navigator.notification.beep` + +## navigator.notification.alert + +顯示一個自訂的è¦å ±æˆ–å°è©±æ–¹å¡Šæ¡†ã€‚ 大多數的科爾多瓦實ç¾ä½¿ç”¨æœ¬æ©Ÿçš„å°è©±æ–¹å¡Šç‚ºæ¤åŠŸèƒ½ï¼Œä½†æŸäº›å¹³è‡ºä¸Šä½¿ç”¨ç€è¦½å™¨çš„ `alert` 功能,這是通常ä¸é‚£éº¼å¯è‡ªè¨‚。 + + navigator.notification.alert(message, alertCallback, [title], [buttonName]) + + +* **message**: 消æ¯å°è©±æ–¹å¡Šã€‚*(String)* + +* **alertCallback**: ç•¶è¦å ±å°è©±æ–¹å¡Šçš„被解雇時è¦èª¿ç”¨çš„回檔。*(函數)* + +* **title**: 標題å°è©±æ–¹å¡Šã€‚*(String)*(å¯é¸ï¼Œé è¨å€¼ç‚º`Alert`) + +* **buttonName**: 按鈕å稱。*(å—串)*(å¯é¸ï¼Œé è¨å€¼ç‚º`OK`) + +### 示例 + + function alertDismissed() { + // do something + } + + navigator.notification.alert( + 'You are the winner!', // message + alertDismissed, // callback + 'Game Over', // title + 'Done' // buttonName + ); + + +### 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± +* iOS +* Tizen +* Windows Phone 7 å’Œ 8 +* Windows 8 +* Windows + +### Windows Phone 7 å’Œ 8 怪癖 + +* 有沒有內置ç€è¦½å™¨è¦å ±ï¼Œä½†ä½ å¯ä»¥ç¶å®šä¸€å€‹ï¼Œå¦‚下所示調用 `alert()` 在全çƒç¯„åœå…§ï¼š + + window.alert = navigator.notification.alert; + + +* 兩個 `alert` å’Œ `confirm` çš„éžé˜»å¡žçš„調用,其ä¸çš„çµæžœæ‰æ˜¯å¯ç”¨çš„éžåŒæ¥ã€‚ + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±æ€ªç™–: + +æœ¬æ©Ÿé˜»æ¢ `window.alert()` å’Œéžé˜»å¡žçš„ `navigator.notification.alert()` 都å¯ã€‚ + +### 黑莓 10 怪癖 + +`navigator.notification.alert ('message'〠confirmCallback〠'title'〠'buttonLabels')` å›žæª”åƒæ•¸è¢«å‚³éžçš„æ•¸ä½ 1。 + +## navigator.notification.confirm + +顯示一個å¯è‡ªè¨‚的確èªå°è©±æ–¹å¡Šã€‚ + + navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels]) + + +* **message**: 消æ¯å°è©±æ–¹å¡Šã€‚*(å—串)* + +* **confirmCallback**: è¦ç”¨ç´¢å¼• (1〠2 或 3) 按下的按鈕,或者在沒有按下按鈕 (0) é§å›žäº†å°è©±æ–¹å¡Šä¸æ™‚調用的回檔。*(函數)* + +* **title**: 標題å°è©±æ–¹å¡Šã€‚*(å—串)*(å¯é¸ï¼Œé è¨å€¼ç‚º`Confirm`) + +* **buttonLabels**: 指定按鈕標籤的å—串陣列。*(陣列)*(å¯é¸ï¼Œé è¨å€¼ç‚º [ `OK,Cancel` ]) + +### confirmCallback + +當使用者按下確èªå°è©±æ–¹å¡Šä¸çš„æŒ‰éˆ•之一時,將執行 `confirmCallback`。 + +回檔需è¦åƒæ•¸ `buttonIndex` *(編號)*ï¼Œå³æŒ‰ä¸‹çš„æŒ‰éˆ•的索引。 請注æ„ç´¢å¼•ä½¿ç”¨ä¸€å€‹åŸºæ–¼ç´¢å¼•ï¼Œå› æ¤å€¼ `1`〠`2`〠`3` ç‰ã€‚ + +### 示例 + + function onConfirm(buttonIndex) { + alert('You selected button ' + buttonIndex); + } + + navigator.notification.confirm( + 'You are the winner!', // message + onConfirm, // callback to invoke with index of button pressed + 'Game Over', // title + ['Restart','Exit'] // buttonLabels + ); + + +### 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± +* iOS +* Tizen +* Windows Phone 7 å’Œ 8 +* Windows 8 +* Windows + +### Windows Phone 7 å’Œ 8 怪癖 + +* 有沒有內置的ç€è¦½å™¨åŠŸèƒ½çš„ `window.confirm` ï¼Œä½†ä½ å¯ä»¥å°‡å®ƒç¶å®šé€šéŽåˆ†é…: + + window.confirm = navigator.notification.confirm; + + +* 調用到 `alert` å’Œ `confirm` çš„éžé˜»å¡žï¼Œæ‰€ä»¥çµæžœå°±æ˜¯åªå¯ç”¨ä»¥éžåŒæ¥æ–¹å¼ã€‚ + +### Windows 的怪癖 + +* 在 Windows8/8.1 它是ä¸å¯èƒ½å°‡è¶…éŽä¸‰å€‹æŒ‰éˆ•æ·»åŠ åˆ° MessageDialog 實例。 + +* 在 Windows Phone 8.1 它是ä¸å¯èƒ½é¡¯ç¤ºæœ‰è¶…éŽå…©å€‹æŒ‰éˆ•çš„å°è©±æ–¹å¡Šã€‚ + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±æ€ªç™–: + +æœ¬æ©Ÿé˜»æ¢ `window.confirm()` å’Œéžé˜»å¡žçš„ `navigator.notification.confirm()` 都å¯ã€‚ + +## navigator.notification.prompt + +顯示本機的å°è©±æ–¹å¡Šï¼Œæ˜¯å¯å®šåˆ¶çš„æ¯”ç€è¦½å™¨çš„ `prompt` 功能。 + + navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText]) + + +* **message**: 消æ¯å°è©±æ–¹å¡Šã€‚*(String)* + +* **promptCallback**: è¦ç”¨æŒ‡æ•¸ (1〠2 或 3) 按下的按鈕或å°è©±æ–¹å¡Šä¸è§£é›‡ç„¡ (0) 按下一個按鈕時調用的回檔。*(函數)* + +* **title**: 標題å°è©±æ–¹å¡Šã€‚*(String)*(å¯é¸ï¼Œé è¨å€¼ç‚º`Alert`) + +* **buttonLabels**: 指定按鈕標籤 (å¯é¸ï¼Œé è¨å€¼ç‚º `["OK","Cancel"]` *(陣列)* çš„å—串陣列) + +* **defaultText**: é è¨æ–‡å—方塊ä¸è¼¸å…¥å€¼ (`å—串`) (å¯é¸ï¼Œé è¨å€¼ï¼š 空å—串) + +### promptCallback + +當使用者按下其ä¸ä¸€å€‹æç¤ºå°è©±æ–¹å¡Šä¸çš„æŒ‰éˆ•時,將執行 `promptCallback`。傳éžçµ¦å›žæª”çš„ `results` 物件包å«ä»¥ä¸‹å±¬æ€§ï¼š + +* **buttonIndex**: 按下的按鈕的索引。*(數)*請注æ„ç´¢å¼•ä½¿ç”¨ä¸€å€‹åŸºæ–¼ç´¢å¼•ï¼Œå› æ¤å€¼ `1`〠`2`〠`3` ç‰ã€‚ + +* **input1**: 在æç¤ºå°è©±æ–¹å¡Šä¸è¼¸å…¥çš„æ–‡æœ¬ã€‚*(å—串)* + +### 示例 + + function onPrompt(results) { + alert("You selected button number " + results.buttonIndex + " and entered " + results.input1); + } + + navigator.notification.prompt( + 'Please enter your name', // message + onPrompt, // callback to invoke + 'Registration', // title + ['Ok','Exit'], // buttonLabels + 'Jane Doe' // defaultText + ); + + +### 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± +* iOS +* Windows Phone 7 å’Œ 8 +* Windows 8 +* Windows + +### Android 的怪癖 + +* Android æ”¯æ´æœ€å¤šçš„三個按鈕,並忽略任何更多。 + +* 在 Android 3.0 åŠæ›´é«˜ç‰ˆæœ¬ï¼Œä½¿ç”¨å…¨æ¯ä¸»é¡Œçš„è¨å‚™ä»¥ç›¸åçš„é †åºé¡¯ç¤ºæŒ‰éˆ•。 + +### Windows 的怪癖 + +* 在 Windows 上æç¤ºå°è©±æ–¹å¡Šæ˜¯åŸºæ–¼ html 的缺ä¹é€™ç¨®æœ¬æ©Ÿ api。 + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±æ€ªç™–: + +æœ¬æ©Ÿé˜»æ¢ `window.prompt()` å’Œéžé˜»å¡žçš„ `navigator.notification.prompt()` 都å¯ã€‚ + +## navigator.notification.beep + +該è¨å‚™æ’放æç¤ºéŸ³çš„è²éŸ³ã€‚ + + navigator.notification.beep(times); + + +* **beep**: 次數é‡è¤‡åœ¨å—¶å—¶è²ã€‚*(數)* + +### 示例 + + // Beep twice! + navigator.notification.beep(2); + + +### 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* iOS +* Tizen +* Windows Phone 7 å’Œ 8 +* Windows 8 + +### 亞馬éœç« OS 怪癖 + +* 亞馬éœç« OS æ’æ”¾é è¨ **è¨ç½®/顯示和è²éŸ³** æ¿ä¸‹æŒ‡å®šçš„ **通知è²éŸ³**。 + +### Android 的怪癖 + +* 安å“ç³»çµ±æ’æ”¾é è¨ **通知鈴è²** **è¨ç½®/è²éŸ³å’Œé¡¯ç¤º** 颿¿ä¸‹æŒ‡å®šã€‚ + +### Windows Phone 7 å’Œ 8 怪癖 + +* ä¾è³´äºŽæ³›åž‹èœ‚鳴音檔從科爾多瓦分佈。 + +### Tizen 怪癖 + +* Tizen é€šéŽæ’放音訊檔通éŽåª’é«” API 實ç¾çš„蜂鳴è²ã€‚ + +* èœ‚é³´éŸ³æª”å¿…é ˆå¾ˆçŸï¼Œå¿…é ˆä½æ–¼æ‡‰ç”¨ç¨‹å¼çš„æ ¹ç›®éŒ„ä¸ï¼Œä¸€å€‹ `è²éŸ³` åç›®éŒ„å’Œå¿…é ˆå°‡å‘½å為 `beep.wav`. diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/package.json b/StoneIsland/plugins/cordova-plugin-dialogs/package.json new file mode 100644 index 00000000..3fd10da8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/package.json @@ -0,0 +1,43 @@ +{ + "name": "cordova-plugin-dialogs", + "version": "1.1.1", + "description": "Cordova Notification Plugin", + "cordova": { + "id": "cordova-plugin-dialogs", + "platforms": [ + "firefoxos", + "android", + "browser", + "amazon-fireos", + "ubuntu", + "ios", + "blackberry10", + "wp7", + "wp8", + "windows8", + "windows" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-dialogs" + }, + "keywords": [ + "cordova", + "notification", + "ecosystem:cordova", + "cordova-firefoxos", + "cordova-android", + "cordova-browser", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-blackberry10", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows" + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/plugin.xml b/StoneIsland/plugins/cordova-plugin-dialogs/plugin.xml new file mode 100644 index 00000000..6d6235fa --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/plugin.xml @@ -0,0 +1,171 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="cordova-plugin-dialogs" + version="1.1.1"> + + <name>Notification</name> + <description>Cordova Notification Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,notification</keywords> + <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-dialogs.git</repo> + <issue>https://issues.apache.org/jira/browse/CB/component/12320642</issue> + + <js-module src="www/notification.js" name="notification"> + <merges target="navigator.notification" /> + </js-module> + + <!-- firefoxos --> + <platform name="firefoxos"> + <config-file target="config.xml" parent="/*"> + <feature name="Notification"> + <param name="firefoxos-package" value="Notification" /> + </feature> + </config-file> + + <asset src="www/firefoxos/notification.css" target="css/notification.css" /> + <asset src="www/firefoxos/danger-press.png" target="img/danger-press.png" /> + <asset src="www/firefoxos/danger.png" target="img/danger.png" /> + <asset src="www/firefoxos/default.png" target="img/default.png" /> + <asset src="www/firefoxos/gradient.png" target="img/gradient.png" /> + <asset src="www/firefoxos/pattern.png" target="img/pattern.png" /> + <asset src="www/firefoxos/recommend.png" target="img/recommend.png" /> + <js-module src="src/firefoxos/notification.js" name="dialogs-impl"> + <runs /> + </js-module> + </platform> + + <!-- android --> + <platform name="android"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="Notification"> + <param name="android-package" value="org.apache.cordova.dialogs.Notification"/> + </feature> + </config-file> + + <source-file src="src/android/Notification.java" target-dir="src/org/apache/cordova/dialogs" /> + + <!-- android specific notification apis --> + <js-module src="www/android/notification.js" name="notification_android"> + <merges target="navigator.notification" /> + </js-module> + + </platform> + + <!-- browser --> + <platform name="browser"> + <js-module src="www/browser/notification.js" name="notification_browser"> + <merges target="navigator.notification" /> + </js-module> + + </platform> + + <!-- amazon-fireos --> + <platform name="amazon-fireos"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="Notification"> + <param name="android-package" value="org.apache.cordova.dialogs.Notification"/> + </feature> + </config-file> + + <source-file src="src/android/Notification.java" target-dir="src/org/apache/cordova/dialogs" /> + + <!-- android specific notification apis --> + <js-module src="www/android/notification.js" name="notification_android"> + <merges target="navigator.notification" /> + </js-module> + + </platform> + + <!-- ubuntu --> + <platform name="ubuntu"> + <header-file src="src/ubuntu/notification.h" /> + <source-file src="src/ubuntu/notification.cpp" /> + <resource-file src="src/ubuntu/notification.qml" /> + </platform> + + <!-- ios --> + <platform name="ios"> + <config-file target="config.xml" parent="/*"> + <feature name="Notification"> + <param name="ios-package" value="CDVNotification"/> + </feature> + </config-file> + <header-file src="src/ios/CDVNotification.h" /> + <source-file src="src/ios/CDVNotification.m" /> + <resource-file src="src/ios/CDVNotification.bundle" /> + <framework src="AudioToolbox.framework" weak="true" /> + </platform> + + <!-- blackberry10 --> + <platform name="blackberry10"> + <source-file src="src/blackberry10/index.js" target-dir="Notification" /> + <config-file target="www/config.xml" parent="/widget"> + <feature name="Notification" value="Notification"/> + </config-file> + <js-module src="www/blackberry10/beep.js" name="beep"> + <clobbers target="window.navigator.notification.beep" /> + </js-module> + <source-file src="www/blackberry10/notification-beep.wav" /> + </platform> + + <!-- wp7 --> + <platform name="wp7"> + <config-file target="config.xml" parent="/*"> + <feature name="Notification"> + <param name="wp-package" value="Notification"/> + </feature> + </config-file> + + <source-file src="src/wp/Notification.cs" /> + <source-file src="src/wp/NotificationBox.xaml.cs" /> + <source-file src="src/wp/NotificationBox.xaml" /> + <source-file src="src/wp/notification-beep.wav" /> + </platform> + + <!-- wp8 --> + <platform name="wp8"> + <config-file target="config.xml" parent="/*"> + <feature name="Notification"> + <param name="wp-package" value="Notification"/> + </feature> + </config-file> + + <source-file src="src/wp/Notification.cs" /> + <source-file src="src/wp/NotificationBox.xaml.cs" /> + <source-file src="src/wp/NotificationBox.xaml" /> + <source-file src="src/wp/notification-beep.wav" /> + </platform> + + <!-- windows8 --> + <platform name="windows8"> + <js-module src="src/windows/NotificationProxy.js" name="NotificationProxy"> + <merges target="" /> + </js-module> + </platform> + + <!-- windows --> + <platform name="windows"> + <js-module src="src/windows/NotificationProxy.js" name="NotificationProxy"> + <merges target="" /> + </js-module> + </platform> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/android/Notification.java b/StoneIsland/plugins/cordova-plugin-dialogs/src/android/Notification.java new file mode 100755 index 00000000..3bc3cee6 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/android/Notification.java @@ -0,0 +1,483 @@ +/* + 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. +*/ +package org.apache.cordova.dialogs; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.AlertDialog.Builder; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import android.media.Ringtone; +import android.media.RingtoneManager; +import android.net.Uri; +import android.widget.EditText; +import android.widget.TextView; + + +/** + * This class provides access to notifications on the device. + * + * Be aware that this implementation gets called on + * navigator.notification.{alert|confirm|prompt}, and that there is a separate + * implementation in org.apache.cordova.CordovaChromeClient that gets + * called on a simple window.{alert|confirm|prompt}. + */ +public class Notification extends CordovaPlugin { + + public int confirmResult = -1; + public ProgressDialog spinnerDialog = null; + public ProgressDialog progressDialog = null; + + /** + * Constructor. + */ + public Notification() { + } + + /** + * Executes the request and returns PluginResult. + * + * @param action The action to execute. + * @param args JSONArray of arguments for the plugin. + * @param callbackContext The callback context used when calling back into JavaScript. + * @return True when the action was valid, false otherwise. + */ + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + /* + * Don't run any of these if the current activity is finishing + * in order to avoid android.view.WindowManager$BadTokenException + * crashing the app. Just return true here since false should only + * be returned in the event of an invalid action. + */ + if(this.cordova.getActivity().isFinishing()) return true; + + if (action.equals("beep")) { + this.beep(args.getLong(0)); + } + else if (action.equals("alert")) { + this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext); + return true; + } + else if (action.equals("confirm")) { + this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext); + return true; + } + else if (action.equals("prompt")) { + this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), callbackContext); + return true; + } + else if (action.equals("activityStart")) { + this.activityStart(args.getString(0), args.getString(1)); + } + else if (action.equals("activityStop")) { + this.activityStop(); + } + else if (action.equals("progressStart")) { + this.progressStart(args.getString(0), args.getString(1)); + } + else if (action.equals("progressValue")) { + this.progressValue(args.getInt(0)); + } + else if (action.equals("progressStop")) { + this.progressStop(); + } + else { + return false; + } + + // Only alert and confirm are async. + callbackContext.success(); + return true; + } + + //-------------------------------------------------------------------------- + // LOCAL METHODS + //-------------------------------------------------------------------------- + + /** + * Beep plays the default notification ringtone. + * + * @param count Number of times to play notification + */ + public void beep(final long count) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone); + + // If phone is not set to silent mode + if (notification != null) { + for (long i = 0; i < count; ++i) { + notification.play(); + long timeout = 5000; + while (notification.isPlaying() && (timeout > 0)) { + timeout = timeout - 100; + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + } + } + } + } + }); + } + + /** + * Builds and shows a native Android alert with given Strings + * @param message The message the alert should display + * @param title The title of the alert + * @param buttonLabel The label of the button + * @param callbackContext The callback context + */ + public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) { + final CordovaInterface cordova = this.cordova; + + Runnable runnable = new Runnable() { + public void run() { + + AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + dlg.setMessage(message); + dlg.setTitle(title); + dlg.setCancelable(true); + dlg.setPositiveButton(buttonLabel, + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); + } + }); + dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { + public void onCancel(DialogInterface dialog) + { + dialog.dismiss(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); + } + }); + + changeTextDirection(dlg); + }; + }; + this.cordova.getActivity().runOnUiThread(runnable); + } + + /** + * Builds and shows a native Android confirm dialog with given title, message, buttons. + * This dialog only shows up to 3 buttons. Any labels after that will be ignored. + * The index of the button pressed will be returned to the JavaScript callback identified by callbackId. + * + * @param message The message the dialog should display + * @param title The title of the dialog + * @param buttonLabels A comma separated list of button labels (Up to 3 buttons) + * @param callbackContext The callback context. + */ + public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) { + final CordovaInterface cordova = this.cordova; + + Runnable runnable = new Runnable() { + public void run() { + AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + dlg.setMessage(message); + dlg.setTitle(title); + dlg.setCancelable(true); + + // First button + if (buttonLabels.length() > 0) { + try { + dlg.setNegativeButton(buttonLabels.getString(0), + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1)); + } + }); + } catch (JSONException e) { } + } + + // Second button + if (buttonLabels.length() > 1) { + try { + dlg.setNeutralButton(buttonLabels.getString(1), + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2)); + } + }); + } catch (JSONException e) { } + } + + // Third button + if (buttonLabels.length() > 2) { + try { + dlg.setPositiveButton(buttonLabels.getString(2), + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3)); + } + }); + } catch (JSONException e) { } + } + dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { + public void onCancel(DialogInterface dialog) + { + dialog.dismiss(); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); + } + }); + + changeTextDirection(dlg); + }; + }; + this.cordova.getActivity().runOnUiThread(runnable); + } + + /** + * Builds and shows a native Android prompt dialog with given title, message, buttons. + * This dialog only shows up to 3 buttons. Any labels after that will be ignored. + * The following results are returned to the JavaScript callback identified by callbackId: + * buttonIndex Index number of the button selected + * input1 The text entered in the prompt dialog box + * + * @param message The message the dialog should display + * @param title The title of the dialog + * @param buttonLabels A comma separated list of button labels (Up to 3 buttons) + * @param callbackContext The callback context. + */ + public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText, final CallbackContext callbackContext) { + + final CordovaInterface cordova = this.cordova; + + Runnable runnable = new Runnable() { + public void run() { + final EditText promptInput = new EditText(cordova.getActivity()); + promptInput.setHint(defaultText); + AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + dlg.setMessage(message); + dlg.setTitle(title); + dlg.setCancelable(true); + + dlg.setView(promptInput); + + final JSONObject result = new JSONObject(); + + // First button + if (buttonLabels.length() > 0) { + try { + dlg.setNegativeButton(buttonLabels.getString(0), + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + try { + result.put("buttonIndex",1); + result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); + } catch (JSONException e) { e.printStackTrace(); } + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); + } + }); + } catch (JSONException e) { } + } + + // Second button + if (buttonLabels.length() > 1) { + try { + dlg.setNeutralButton(buttonLabels.getString(1), + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + try { + result.put("buttonIndex",2); + result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); + } catch (JSONException e) { e.printStackTrace(); } + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); + } + }); + } catch (JSONException e) { } + } + + // Third button + if (buttonLabels.length() > 2) { + try { + dlg.setPositiveButton(buttonLabels.getString(2), + new AlertDialog.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + try { + result.put("buttonIndex",3); + result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); + } catch (JSONException e) { e.printStackTrace(); } + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); + } + }); + } catch (JSONException e) { } + } + dlg.setOnCancelListener(new AlertDialog.OnCancelListener() { + public void onCancel(DialogInterface dialog){ + dialog.dismiss(); + try { + result.put("buttonIndex",0); + result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText()); + } catch (JSONException e) { e.printStackTrace(); } + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); + } + }); + + changeTextDirection(dlg); + }; + }; + this.cordova.getActivity().runOnUiThread(runnable); + } + + /** + * Show the spinner. + * + * @param title Title of the dialog + * @param message The message of the dialog + */ + public synchronized void activityStart(final String title, final String message) { + if (this.spinnerDialog != null) { + this.spinnerDialog.dismiss(); + this.spinnerDialog = null; + } + final Notification notification = this; + final CordovaInterface cordova = this.cordova; + Runnable runnable = new Runnable() { + public void run() { + notification.spinnerDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + notification.spinnerDialog.setTitle(title); + notification.spinnerDialog.setMessage(message); + notification.spinnerDialog.setCancelable(true); + notification.spinnerDialog.setIndeterminate(true); + notification.spinnerDialog.setOnCancelListener( + new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + notification.spinnerDialog = null; + } + }); + notification.spinnerDialog.show(); + } + }; + this.cordova.getActivity().runOnUiThread(runnable); + } + + /** + * Stop spinner. + */ + public synchronized void activityStop() { + if (this.spinnerDialog != null) { + this.spinnerDialog.dismiss(); + this.spinnerDialog = null; + } + } + + /** + * Show the progress dialog. + * + * @param title Title of the dialog + * @param message The message of the dialog + */ + public synchronized void progressStart(final String title, final String message) { + if (this.progressDialog != null) { + this.progressDialog.dismiss(); + this.progressDialog = null; + } + final Notification notification = this; + final CordovaInterface cordova = this.cordova; + Runnable runnable = new Runnable() { + public void run() { + notification.progressDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + notification.progressDialog.setTitle(title); + notification.progressDialog.setMessage(message); + notification.progressDialog.setCancelable(true); + notification.progressDialog.setMax(100); + notification.progressDialog.setProgress(0); + notification.progressDialog.setOnCancelListener( + new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + notification.progressDialog = null; + } + }); + notification.progressDialog.show(); + } + }; + this.cordova.getActivity().runOnUiThread(runnable); + } + + /** + * Set value of progress bar. + * + * @param value 0-100 + */ + public synchronized void progressValue(int value) { + if (this.progressDialog != null) { + this.progressDialog.setProgress(value); + } + } + + /** + * Stop progress dialog. + */ + public synchronized void progressStop() { + if (this.progressDialog != null) { + this.progressDialog.dismiss(); + this.progressDialog = null; + } + } + + @SuppressLint("NewApi") + private AlertDialog.Builder createDialog(CordovaInterface cordova) { + int currentapiVersion = android.os.Build.VERSION.SDK_INT; + if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) { + return new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + } else { + return new AlertDialog.Builder(cordova.getActivity()); + } + } + + @SuppressLint("InlinedApi") + private ProgressDialog createProgressDialog(CordovaInterface cordova) { + int currentapiVersion = android.os.Build.VERSION.SDK_INT; + if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + return new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT); + } else { + return new ProgressDialog(cordova.getActivity()); + } + } + + @SuppressLint("NewApi") + private void changeTextDirection(Builder dlg){ + int currentapiVersion = android.os.Build.VERSION.SDK_INT; + dlg.create(); + AlertDialog dialog = dlg.show(); + if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { + TextView messageview = (TextView)dialog.findViewById(android.R.id.message); + messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE); + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/blackberry10/index.js b/StoneIsland/plugins/cordova-plugin-dialogs/src/blackberry10/index.js new file mode 100644 index 00000000..3660f667 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/blackberry10/index.js @@ -0,0 +1,87 @@ +/* +* Copyright 2013 Research In Motion Limited. +* +* Licensed 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 showDialog(args, dialogType, result) { + //Unpack and map the args + var msg = JSON.parse(decodeURIComponent(args[0])), + title = JSON.parse(decodeURIComponent(args[1])), + btnLabel = JSON.parse(decodeURIComponent(args[2])); + + if (!Array.isArray(btnLabel)) { + //Converts to array for (string) and (string,string, ...) cases + btnLabel = btnLabel.split(","); + } + + if (msg && typeof msg === "string") { + msg = msg.replace(/^"|"$/g, "").replace(/\\"/g, '"'); + } else { + result.error("message is undefined"); + return; + } + + var messageObj = { + title : title, + htmlmessage : msg, + dialogType : dialogType, + optionalButtons : btnLabel + }; + + //TODO replace with getOverlayWebview() when available in webplatform + qnx.webplatform.getWebViews()[2].dialog.show(messageObj, function (data) { + if (typeof data === "number") { + //Confirm dialog call back needs to be called with one-based indexing [1,2,3 etc] + result.callbackOk(++data, false); + } else { + //Prompt dialog callback expects object + result.callbackOk({ + buttonIndex: data.ok ? 1 : 0, + input1: (data.oktext) ? decodeURIComponent(data.oktext) : "" + }, false); + } + }); + + result.noResult(true); +} + +module.exports = { + alert: function (success, fail, args, env) { + var result = new PluginResult(args, env); + + if (Object.keys(args).length < 3) { + result.error("Notification action - alert arguments not found."); + } else { + showDialog(args, "CustomAsk", result); + } + }, + confirm: function (success, fail, args, env) { + var result = new PluginResult(args, env); + + if (Object.keys(args).length < 3) { + result.error("Notification action - confirm arguments not found."); + } else { + showDialog(args, "CustomAsk", result); + } + }, + prompt: function (success, fail, args, env) { + var result = new PluginResult(args, env); + + if (Object.keys(args).length < 3) { + result.error("Notification action - prompt arguments not found."); + } else { + showDialog(args, "JavaScriptPrompt", result); + } + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/firefoxos/notification.js b/StoneIsland/plugins/cordova-plugin-dialogs/src/firefoxos/notification.js new file mode 100644 index 00000000..b6986fd0 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/firefoxos/notification.js @@ -0,0 +1,154 @@ +/* + * + * 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 modulemapper = require('cordova/modulemapper'); + + +var origOpenFunc = modulemapper.getOriginalSymbol(window, 'window.open'); + + +function _empty() {} + + +function modal(message, callback, title, buttonLabels, domObjects) { + var mainWindow = window; + var modalWindow = origOpenFunc(); + var modalDocument = modalWindow.document; + + modalDocument.write( + '<html><head>' + + '<link rel="stylesheet" type="text/css" href="/css/index.css" />' + + '<link rel="stylesheet" type="text/css" href="/css/notification.css" />' + + '</head><body></body></html>'); + + var box = modalDocument.createElement('form'); + box.setAttribute('role', 'dialog'); + // prepare and append empty section + var section = modalDocument.createElement('section'); + box.appendChild(section); + // add title + var boxtitle = modalDocument.createElement('h1'); + boxtitle.appendChild(modalDocument.createTextNode(title)); + section.appendChild(boxtitle); + // add message + var boxMessage = modalDocument.createElement('p'); + boxMessage.appendChild(modalDocument.createTextNode(message)); + section.appendChild(boxMessage); + // inject what's needed + if (domObjects) { + section.appendChild(domObjects); + } + // add buttons and assign callbackButton on click + var menu = modalDocument.createElement('menu'); + box.appendChild(menu); + for (var index = 0; index < buttonLabels.length; index++) { + addButton(buttonLabels[index], index, (index === 0)); + } + modalDocument.body.appendChild(box); + + function addButton(label, index, recommended) { + var thisButtonCallback = makeCallbackButton(index + 1); + var button = modalDocument.createElement('button'); + button.appendChild(modalDocument.createTextNode(label)); + button.addEventListener('click', thisButtonCallback, false); + if (recommended) { + // TODO: default one listens to Enter key + button.classList.add('recommend'); + } + menu.appendChild(button); + } + + // TODO: onUnload listens to the cancel key + function onUnload() { + var result = 0; + if (modalDocument.getElementById('prompt-input')) { + result = { + input1: '', + buttonIndex: 0 + } + } + mainWindow.setTimeout(function() { + callback(result); + }, 10); + }; + modalWindow.addEventListener('unload', onUnload, false); + + // call callback and destroy modal + function makeCallbackButton(labelIndex) { + return function() { + if (modalWindow) { + modalWindow.removeEventListener('unload', onUnload, false); + modalWindow.close(); + } + // checking if prompt + var promptInput = modalDocument.getElementById('prompt-input'); + var response; + if (promptInput) { + response = { + input1: promptInput.value, + buttonIndex: labelIndex + }; + } + response = response || labelIndex; + callback(response); + } + } +} + +var Notification = { + vibrate: function(milliseconds) { + navigator.vibrate(milliseconds); + }, + alert: function(successCallback, errorCallback, args) { + var message = args[0]; + var title = args[1]; + var _buttonLabels = [args[2]]; + var _callback = (successCallback || _empty); + modal(message, _callback, title, _buttonLabels); + }, + confirm: function(successCallback, errorCallback, args) { + var message = args[0]; + var title = args[1]; + var buttonLabels = args[2]; + var _callback = (successCallback || _empty); + modal(message, _callback, title, buttonLabels); + }, + prompt: function(successCallback, errorCallback, args) { + var message = args[0]; + var title = args[1]; + var buttonLabels = args[2]; + var defaultText = args[3]; + var inputParagraph = document.createElement('p'); + inputParagraph.classList.add('input'); + var inputElement = document.createElement('input'); + inputElement.setAttribute('type', 'text'); + inputElement.id = 'prompt-input'; + if (defaultText) { + inputElement.setAttribute('placeholder', defaultText); + } + inputParagraph.appendChild(inputElement); + modal(message, successCallback, title, buttonLabels, inputParagraph); + } +}; + + +module.exports = Notification; +require('cordova/exec/proxy').add('Notification', Notification); diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.bundle/beep.wav b/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.bundle/beep.wav Binary files differnew file mode 100644 index 00000000..05f5997f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.bundle/beep.wav diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.h b/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.h new file mode 100644 index 00000000..9253f6a9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.h @@ -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 <Foundation/Foundation.h> +#import <UIKit/UIKit.h> +#import <AudioToolbox/AudioServices.h> +#import <Cordova/CDVPlugin.h> + +@interface CDVNotification : CDVPlugin <UIAlertViewDelegate>{} + +- (void)alert:(CDVInvokedUrlCommand*)command; +- (void)confirm:(CDVInvokedUrlCommand*)command; +- (void)prompt:(CDVInvokedUrlCommand*)command; +- (void)beep:(CDVInvokedUrlCommand*)command; + +@end + +@interface CDVAlertView : UIAlertView {} +@property (nonatomic, copy) NSString* callbackId; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.m b/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.m new file mode 100644 index 00000000..1581ad3c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/ios/CDVNotification.m @@ -0,0 +1,221 @@ +/* + 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 "CDVNotification.h" + +#define DIALOG_TYPE_ALERT @"alert" +#define DIALOG_TYPE_PROMPT @"prompt" + +static void soundCompletionCallback(SystemSoundID ssid, void* data); + +@implementation CDVNotification + +/* + * showDialogWithMessage - Common method to instantiate the alert view for alert, confirm, and prompt notifications. + * Parameters: + * message The alert view message. + * title The alert view title. + * buttons The array of customized strings for the buttons. + * defaultText The input text for the textbox (if textbox exists). + * callbackId The commmand callback id. + * dialogType The type of alert view [alert | prompt]. + */ +- (void)showDialogWithMessage:(NSString*)message title:(NSString*)title buttons:(NSArray*)buttons defaultText:(NSString*)defaultText callbackId:(NSString*)callbackId dialogType:(NSString*)dialogType +{ + + NSUInteger count = [buttons count]; +#ifdef __IPHONE_8_0 + if (NSClassFromString(@"UIAlertController")) { + + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; + + if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.3) { + + CGRect alertFrame = [UIScreen mainScreen].applicationFrame; + + if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) { + // swap the values for the app frame since it is now in landscape + CGFloat temp = alertFrame.size.width; + alertFrame.size.width = alertFrame.size.height; + alertFrame.size.height = temp; + } + + alertController.view.frame = alertFrame; + } + + for (int n = 0; n < count; n++) { + + UIAlertAction* action = [UIAlertAction actionWithTitle:[buttons objectAtIndex:n] style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) + { + CDVPluginResult* result; + + if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) { + + NSString* value0 = [[alertController.textFields objectAtIndex:0] text]; + NSDictionary* info = @{ + @"buttonIndex":@(n + 1), + @"input1":(value0 ? value0 : [NSNull null]) + }; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:info]; + + } else { + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)(n + 1)]; + + } + + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + + }]; + [alertController addAction:action]; + + } + + if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) { + + [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) { + textField.text = defaultText; + }]; + } + + + + [self.viewController presentViewController:alertController animated:YES completion:nil]; + + } else { +#endif + CDVAlertView* alertView = [[CDVAlertView alloc] + initWithTitle:title + message:message + delegate:self + cancelButtonTitle:nil + otherButtonTitles:nil]; + + alertView.callbackId = callbackId; + + + + for (int n = 0; n < count; n++) { + [alertView addButtonWithTitle:[buttons objectAtIndex:n]]; + } + + if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) { + alertView.alertViewStyle = UIAlertViewStylePlainTextInput; + UITextField* textField = [alertView textFieldAtIndex:0]; + textField.text = defaultText; + } + + [alertView show]; +#ifdef __IPHONE_8_0 + } +#endif + +} + +- (void)alert:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* message = [command argumentAtIndex:0]; + NSString* title = [command argumentAtIndex:1]; + NSString* buttons = [command argumentAtIndex:2]; + + [self showDialogWithMessage:message title:title buttons:@[buttons] defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT]; +} + +- (void)confirm:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* message = [command argumentAtIndex:0]; + NSString* title = [command argumentAtIndex:1]; + NSArray* buttons = [command argumentAtIndex:2]; + + [self showDialogWithMessage:message title:title buttons:buttons defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT]; +} + +- (void)prompt:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* message = [command argumentAtIndex:0]; + NSString* title = [command argumentAtIndex:1]; + NSArray* buttons = [command argumentAtIndex:2]; + NSString* defaultText = [command argumentAtIndex:3]; + + [self showDialogWithMessage:message title:title buttons:buttons defaultText:defaultText callbackId:callbackId dialogType:DIALOG_TYPE_PROMPT]; +} + +/** + * Callback invoked when an alert dialog's buttons are clicked. + */ +- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex +{ + CDVAlertView* cdvAlertView = (CDVAlertView*)alertView; + CDVPluginResult* result; + + // Determine what gets returned to JS based on the alert view type. + if (alertView.alertViewStyle == UIAlertViewStyleDefault) { + // For alert and confirm, return button index as int back to JS. + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)(buttonIndex + 1)]; + } else { + // For prompt, return button index and input text back to JS. + NSString* value0 = [[alertView textFieldAtIndex:0] text]; + NSDictionary* info = @{ + @"buttonIndex":@(buttonIndex + 1), + @"input1":(value0 ? value0 : [NSNull null]) + }; + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:info]; + } + [self.commandDelegate sendPluginResult:result callbackId:cdvAlertView.callbackId]; +} + +static void playBeep(int count) { + SystemSoundID completeSound; + NSInteger cbDataCount = count; + NSURL* audioPath = [[NSBundle mainBundle] URLForResource:@"CDVNotification.bundle/beep" withExtension:@"wav"]; + #if __has_feature(objc_arc) + AudioServicesCreateSystemSoundID((__bridge CFURLRef)audioPath, &completeSound); + #else + AudioServicesCreateSystemSoundID((CFURLRef)audioPath, &completeSound); + #endif + AudioServicesAddSystemSoundCompletion(completeSound, NULL, NULL, soundCompletionCallback, (void*)(cbDataCount-1)); + AudioServicesPlaySystemSound(completeSound); +} + +static void soundCompletionCallback(SystemSoundID ssid, void* data) { + int count = (int)data; + AudioServicesRemoveSystemSoundCompletion (ssid); + AudioServicesDisposeSystemSoundID(ssid); + if (count > 0) { + playBeep(count); + } +} + +- (void)beep:(CDVInvokedUrlCommand*)command +{ + NSNumber* count = [command argumentAtIndex:0 withDefault:[NSNumber numberWithInt:1]]; + playBeep([count intValue]); +} + + +@end + +@implementation CDVAlertView + +@synthesize callbackId; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.cpp b/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.cpp new file mode 100644 index 00000000..d0adf892 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.cpp @@ -0,0 +1,85 @@ +/* + * + * Licensed 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 "notification.h" + +#include <QApplication> + +void Dialogs::beep(int scId, int ecId, int times) { + Q_UNUSED(scId) + Q_UNUSED(ecId) + Q_UNUSED(times) + + _player.setVolume(100); + _player.setMedia(QUrl::fromLocalFile("/usr/share/sounds/ubuntu/stereo/bell.ogg")); + _player.play(); +} + +void Dialogs::alert(int scId, int ecId, const QString &message, const QString &title, const QString &buttonLabel) { + QStringList list; + list.append(buttonLabel); + + confirm(scId, ecId, message, title, list); +} + +void Dialogs::confirm(int scId, int ecId, const QString &message, const QString &title, const QStringList &buttonLabels) { + Q_UNUSED(ecId); + + if (_alertCallback) { + qCritical() << "can't open second dialog"; + return; + } + _alertCallback = scId; + + QString s1, s2, s3; + if (buttonLabels.size() > 0) + s1 = buttonLabels[0]; + if (buttonLabels.size() > 1) + s2 = buttonLabels[1]; + if (buttonLabels.size() > 2) + s3 = buttonLabels[2]; + + QString path = m_cordova->get_app_dir() + "/../qml/notification.qml"; + QString qml = QString("PopupUtils.open(%1, root, { root: root, cordova: cordova, title: %2, text: %3, promptVisible: false, button1Text: %4, button2Text: %5, button3Text: %6 })") + .arg(CordovaInternal::format(path)).arg(CordovaInternal::format(title)).arg(CordovaInternal::format(message)) + .arg(CordovaInternal::format(s1)).arg(CordovaInternal::format(s2)).arg(CordovaInternal::format(s3)); + + m_cordova->execQML(qml); +} + +void Dialogs::prompt(int scId, int ecId, const QString &message, const QString &title, const QStringList &buttonLabels, const QString &defaultText) { + Q_UNUSED(ecId); + + if (_alertCallback) { + qCritical() << "can't open second dialog"; + return; + } + _alertCallback = scId; + + QString s1, s2, s3; + if (buttonLabels.size() > 0) + s1 = buttonLabels[0]; + if (buttonLabels.size() > 1) + s2 = buttonLabels[1]; + if (buttonLabels.size() > 2) + s3 = buttonLabels[2]; + QString path = m_cordova->get_app_dir() + "/../qml/notification.qml"; + QString qml = QString("PopupUtils.open(%1, root, { root: root, cordova: cordova, title: %2, text: %3, promptVisible: true, defaultPromptText: %7, button1Text: %4, button2Text: %5, button3Text: %6 })") + .arg(CordovaInternal::format(path)).arg(CordovaInternal::format(title)).arg(CordovaInternal::format(message)) + .arg(CordovaInternal::format(s1)).arg(CordovaInternal::format(s2)) + .arg(CordovaInternal::format(s3)).arg(CordovaInternal::format(defaultText)); + + m_cordova->execQML(qml); +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.h b/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.h new file mode 100644 index 00000000..53430738 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.h @@ -0,0 +1,64 @@ +/* + * + * Licensed 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 NOTIFICATION_H +#define NOTIFICATION_H + +#include <QtQuick> +#include <QMediaPlayer> +#include <cplugin.h> +#include <cordova.h> + +class Dialogs: public CPlugin { + Q_OBJECT +public: + explicit Dialogs(Cordova *cordova): CPlugin(cordova), _alertCallback(0) { + } + + virtual const QString fullName() override { + return Dialogs::fullID(); + } + + virtual const QString shortName() override { + return "Notification"; + } + + static const QString fullID() { + return "Notification"; + } +public slots: + void beep(int scId, int ecId, int times); + void alert(int scId, int ecId, const QString &message, const QString &title, const QString &buttonLabel); + void confirm(int scId, int ecId, const QString &message, const QString &title, const QStringList &buttonLabels); + void prompt(int scId, int ecId, const QString &message, const QString &title, const QStringList &buttonLabels, const QString &defaultText); + + void notificationDialogButtonPressed(int buttonId, const QString &text, bool prompt) { + if (prompt) { + QVariantMap res; + res.insert("buttonIndex", buttonId); + res.insert("input1", text); + this->cb(_alertCallback, res); + } else { + this->cb(_alertCallback, buttonId); + } + _alertCallback = 0; + } + +private: + int _alertCallback; + QMediaPlayer _player; +}; + +#endif diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.qml b/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.qml new file mode 100644 index 00000000..5fdc7d31 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/ubuntu/notification.qml @@ -0,0 +1,65 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +import QtQuick 2.0 +import Ubuntu.Components.Popups 0.1 +import Ubuntu.Components 0.1 + +Dialog { + id: dialogue + property string button1Text + property string button2Text + property string button3Text + property bool promptVisible + property string defaultPromptText + + TextField { + id: prompt + text: defaultPromptText + visible: promptVisible + focus: true + } + Button { + text: button1Text + color: "orange" + onClicked: { + root.exec("Notification", "notificationDialogButtonPressed", [1, prompt.text, promptVisible]); + PopupUtils.close(dialogue) + } + } + Button { + text: button2Text + visible: button2Text.length > 0 + color: "orange" + onClicked: { + root.exec("Notification", "notificationDialogButtonPressed", [2, prompt.text, promptVisible]); + PopupUtils.close(dialogue) + } + } + Button { + text: button3Text + visible: button3Text.length > 0 + onClicked: { + root.exec("Notification", "notificationDialogButtonPressed", [3, prompt.text, promptVisible]); + PopupUtils.close(dialogue) + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/windows/NotificationProxy.js b/StoneIsland/plugins/cordova-plugin-dialogs/src/windows/NotificationProxy.js new file mode 100644 index 00000000..d1eb3448 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/windows/NotificationProxy.js @@ -0,0 +1,249 @@ +/* + * + * 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 Windows:true */ + +var cordova = require('cordova'); + +var isAlertShowing = false; +var alertStack = []; + +// CB-8928: When toStaticHTML is undefined, prompt fails to run +function _cleanHtml(html) { return html; } +if (typeof toStaticHTML !== 'undefined') { + _cleanHtml = toStaticHTML; +} + +// Windows does not provide native UI for promp dialog so we use some +// simple html-based implementation until it is available +function createPromptDialog(title, message, buttons, defaultText, callback) { + + var isPhone = cordova.platformId == "windows" && WinJS.Utilities.isPhone;; + + var dlgWrap = document.createElement("div"); + dlgWrap.style.position = "absolute"; + dlgWrap.style.width = "100%"; + dlgWrap.style.height = "100%"; + dlgWrap.style.backgroundColor = "rgba(0,0,0,0.25)"; + dlgWrap.style.zIndex = "100000"; + + var dlg = document.createElement("div"); + dlg.style.width = "100%"; + dlg.style.minHeight = "180px"; + dlg.style.height = "auto"; + dlg.style.overflow = "auto"; + dlg.style.backgroundColor = "white"; + dlg.style.position = "relative"; + dlg.style.lineHeight = "2"; + + if (isPhone) { + dlg.style.padding = "0px 5%"; + } else { + dlg.style.top = "50%"; // center vertically + dlg.style.transform = "translateY(-50%)"; + dlg.style.padding = "0px 30%"; + } + + // dialog layout template + dlg.innerHTML = _cleanHtml("<span id='lbl-title' style='font-size: 24pt'></span><br/>" // title + + "<span id='lbl-message'></span><br/>" // message + + "<input id='prompt-input' style='width: 100%'/><br/>"); // input fields + + dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title)); + dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message)); + dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText); + + function makeButtonCallback(idx) { + return function () { + var value = promptInput = dlg.querySelector('#prompt-input').value; + dlgWrap.parentNode.removeChild(dlgWrap); + + if (callback) { + callback({ input1: value, buttonIndex: idx }); + } + } + } + + function addButton(idx, label) { + var button = document.createElement('button'); + button.style.margin = "8px 0 8px 16px"; + button.style.float = "right"; + button.style.fontSize = "12pt"; + button.tabIndex = idx; + button.onclick = makeButtonCallback(idx + 1); + if (idx == 0) { + button.style.color = "white"; + button.style.backgroundColor = "#464646"; + } else { + button.style.backgroundColor = "#cccccc"; + } + button.style.border = "none"; + button.appendChild(document.createTextNode(label)); + dlg.appendChild(button); + } + + // reverse order is used since we align buttons to the right + for (var idx = buttons.length - 1; idx >= 0; idx--) { + addButton(idx, buttons[idx]); + } + + dlgWrap.appendChild(dlg); + document.body.appendChild(dlgWrap); + + // make sure input field is under focus + dlg.querySelector('#prompt-input').focus(); + + return dlgWrap; +} + +module.exports = { + alert:function(win, loseX, args) { + + if (isAlertShowing) { + var later = function () { + module.exports.alert(win, loseX, args); + }; + alertStack.push(later); + return; + } + isAlertShowing = true; + + var message = args[0]; + var _title = args[1]; + var _buttonLabel = args[2]; + + var md = new Windows.UI.Popups.MessageDialog(message, _title); + md.commands.append(new Windows.UI.Popups.UICommand(_buttonLabel)); + md.showAsync().then(function() { + isAlertShowing = false; + win && win(); + + if (alertStack.length) { + setTimeout(alertStack.shift(), 0); + } + + }); + }, + + prompt: function (win, lose, args) { + if (isAlertShowing) { + var later = function () { + module.exports.prompt(win, lose, args); + }; + alertStack.push(later); + return; + } + + isAlertShowing = true; + + var message = args[0], + title = args[1], + buttons = args[2], + defaultText = args[3]; + + try { + createPromptDialog(title, message, buttons, defaultText, function (evt) { + isAlertShowing = false; + if (win) { + win(evt); + } + }); + + } catch (e) { + // set isAlertShowing flag back to false in case of exception + isAlertShowing = false; + if (alertStack.length) { + setTimeout(alertStack.shift(), 0); + } + // rethrow exception + throw e; + } + }, + + confirm:function(win, loseX, args) { + + if (isAlertShowing) { + var later = function () { + module.exports.confirm(win, loseX, args); + }; + alertStack.push(later); + return; + } + + isAlertShowing = true; + + try { + var message = args[0]; + var _title = args[1]; + var buttons = args[2]; + + var md = new Windows.UI.Popups.MessageDialog(message, _title); + + buttons.forEach(function(buttonLabel) { + md.commands.append(new Windows.UI.Popups.UICommand(buttonLabel)); + }); + + md.showAsync().then(function(res) { + isAlertShowing = false; + var result = res ? buttons.indexOf(res.label) + 1 : 0; + win && win(result); + if (alertStack.length) { + setTimeout(alertStack.shift(), 0); + } + + }); + } catch (e) { + // set isAlertShowing flag back to false in case of exception + isAlertShowing = false; + if (alertStack.length) { + setTimeout(alertStack.shift(), 0); + } + // rethrow exception + throw e; + } + }, + + beep:function(winX, loseX, args) { + + // set a default args if it is not set + args = args && args.length ? args : ["1"]; + + var snd = new Audio('ms-winsoundevent:Notification.Default'); + var count = parseInt(args[0]) || 1; + snd.msAudioCategory = "Alerts"; + + var onEvent = function () { + if (count > 0) { + snd.play(); + } else { + snd.removeEventListener("ended", onEvent); + snd = null; + winX && winX(); // notification.js just sends null, but this is future friendly + } + count--; + }; + snd.addEventListener("ended", onEvent); + onEvent(); + + } +}; + +require("cordova/exec/proxy").add("Notification",module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/Notification.cs b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/Notification.cs new file mode 100644 index 00000000..b6216848 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/Notification.cs @@ -0,0 +1,482 @@ +/* + Licensed 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. +*/ + +using System; +using System.Windows; +using System.Windows.Controls; +using Microsoft.Devices; +using System.Runtime.Serialization; +using System.Threading; +using System.Windows.Resources; +using Microsoft.Phone.Controls; +using Microsoft.Xna.Framework.Audio; +using WPCordovaClassLib.Cordova.UI; +using System.Diagnostics; + + +namespace WPCordovaClassLib.Cordova.Commands +{ + public class Notification : BaseCommand + { + static ProgressBar progressBar = null; + const int DEFAULT_DURATION = 5; + + private NotificationBox notifyBox; + + private class NotifBoxData + { + public NotificationBox previous {get;set;} + public string callbackId { get; set; } + } + + private PhoneApplicationPage Page + { + get + { + PhoneApplicationPage page = null; + PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; + if (frame != null) + { + page = frame.Content as PhoneApplicationPage; + } + return page; + } + } + + // blink api - doesn't look like there is an equivalent api we can use... + + [DataContract] + public class AlertOptions + { + [OnDeserializing] + public void OnDeserializing(StreamingContext context) + { + // set defaults + this.message = "message"; + this.title = "Alert"; + this.buttonLabel = "ok"; + } + + /// <summary> + /// message to display in the alert box + /// </summary> + [DataMember] + public string message; + + /// <summary> + /// title displayed on the alert window + /// </summary> + [DataMember] + public string title; + + /// <summary> + /// text to display on the button + /// </summary> + [DataMember] + public string buttonLabel; + } + + [DataContract] + public class PromptResult + { + [DataMember] + public int buttonIndex; + + [DataMember] + public string input1; + + public PromptResult(int index, string text) + { + this.buttonIndex = index; + this.input1 = text; + } + } + + public void alert(string options) + { + string[] args = JSON.JsonHelper.Deserialize<string[]>(options); + AlertOptions alertOpts = new AlertOptions(); + alertOpts.message = args[0]; + alertOpts.title = args[1]; + alertOpts.buttonLabel = args[2]; + string aliasCurrentCommandCallbackId = args[3]; + + Deployment.Current.Dispatcher.BeginInvoke(() => + { + PhoneApplicationPage page = Page; + if (page != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + var previous = notifyBox; + notifyBox = new NotificationBox(); + notifyBox.Tag = new NotifBoxData { previous = previous, callbackId = aliasCurrentCommandCallbackId }; + notifyBox.PageTitle.Text = alertOpts.title; + notifyBox.SubTitle.Text = alertOpts.message; + Button btnOK = new Button(); + btnOK.Content = alertOpts.buttonLabel; + btnOK.Click += new RoutedEventHandler(btnOK_Click); + btnOK.Tag = 1; + notifyBox.ButtonPanel.Children.Add(btnOK); + grid.Children.Add(notifyBox); + + if (previous == null) + { + page.BackKeyPress += page_BackKeyPress; + } + } + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION)); + } + }); + } + + public void prompt(string options) + { + string[] args = JSON.JsonHelper.Deserialize<string[]>(options); + string message = args[0]; + string title = args[1]; + string buttonLabelsArray = args[2]; + string[] buttonLabels = JSON.JsonHelper.Deserialize<string[]>(buttonLabelsArray); + string defaultText = args[3]; + string aliasCurrentCommandCallbackId = args[4]; + + Deployment.Current.Dispatcher.BeginInvoke(() => + { + PhoneApplicationPage page = Page; + if (page != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + var previous = notifyBox; + notifyBox = new NotificationBox(); + notifyBox.Tag = new NotifBoxData { previous = previous, callbackId = aliasCurrentCommandCallbackId }; + notifyBox.PageTitle.Text = title; + notifyBox.SubTitle.Text = message; + + //TextBox textBox = new TextBox(); + //textBox.Text = defaultText; + //textBox.AcceptsReturn = true; + //notifyBox.ContentScroller.Content = textBox; + + notifyBox.InputText.Text = defaultText; + notifyBox.InputText.Visibility = Visibility.Visible; + + for (int i = 0; i < buttonLabels.Length; ++i) + { + Button button = new Button(); + button.Content = buttonLabels[i]; + button.Tag = i + 1; + button.Click += promptBoxbutton_Click; + notifyBox.ButtonPanel.Orientation = Orientation.Vertical; + notifyBox.ButtonPanel.Children.Add(button); + } + + grid.Children.Add(notifyBox); + if (previous != null) + { + page.BackKeyPress += page_BackKeyPress; + } + } + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION)); + } + }); + } + + public void confirm(string options) + { + string[] args = JSON.JsonHelper.Deserialize<string[]>(options); + AlertOptions alertOpts = new AlertOptions(); + alertOpts.message = args[0]; + alertOpts.title = args[1]; + alertOpts.buttonLabel = args[2]; + string aliasCurrentCommandCallbackId = args[3]; + + Deployment.Current.Dispatcher.BeginInvoke(() => + { + PhoneApplicationPage page = Page; + if (page != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + var previous = notifyBox; + notifyBox = new NotificationBox(); + notifyBox.Tag = new NotifBoxData { previous = previous, callbackId = aliasCurrentCommandCallbackId }; + notifyBox.PageTitle.Text = alertOpts.title; + notifyBox.SubTitle.Text = alertOpts.message; + + string[] labels = JSON.JsonHelper.Deserialize<string[]>(alertOpts.buttonLabel); + + if (labels == null) + { + labels = alertOpts.buttonLabel.Split(','); + } + + for (int n = 0; n < labels.Length; n++) + { + Button btn = new Button(); + btn.Content = labels[n]; + btn.Tag = n; + btn.Click += new RoutedEventHandler(btnOK_Click); + notifyBox.ButtonPanel.Children.Add(btn); + } + + grid.Children.Add(notifyBox); + if (previous == null) + { + page.BackKeyPress += page_BackKeyPress; + } + } + } + else + { + DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION)); + } + }); + } + + void promptBoxbutton_Click(object sender, RoutedEventArgs e) + { + Button button = sender as Button; + FrameworkElement promptBox = null; + int buttonIndex = 0; + string callbackId = string.Empty; + string text = string.Empty; + if (button != null) + { + buttonIndex = (int)button.Tag; + promptBox = button.Parent as FrameworkElement; + while ((promptBox = promptBox.Parent as FrameworkElement) != null && + !(promptBox is NotificationBox)) ; + } + + if (promptBox != null) + { + NotificationBox box = promptBox as NotificationBox; + + text = box.InputText.Text; + + PhoneApplicationPage page = Page; + if (page != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + grid.Children.Remove(promptBox); + } + + NotifBoxData data = promptBox.Tag as NotifBoxData; + promptBox = data.previous as NotificationBox; + callbackId = data.callbackId as string; + + if (promptBox == null) + { + page.BackKeyPress -= page_BackKeyPress; + } + } + } + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new PromptResult(buttonIndex, text)), callbackId); + } + + void page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) + { + PhoneApplicationPage page = sender as PhoneApplicationPage; + string callbackId = ""; + if (page != null && notifyBox != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + grid.Children.Remove(notifyBox); + NotifBoxData notifBoxData = notifyBox.Tag as NotifBoxData; + notifyBox = notifBoxData.previous as NotificationBox; + callbackId = notifBoxData.callbackId as string; + } + if (notifyBox == null) + { + page.BackKeyPress -= page_BackKeyPress; + } + e.Cancel = true; + } + + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, 0), callbackId); + } + + void btnOK_Click(object sender, RoutedEventArgs e) + { + Button btn = sender as Button; + FrameworkElement notifBoxParent = null; + int retVal = 0; + string callbackId = ""; + if (btn != null) + { + retVal = (int)btn.Tag + 1; + + notifBoxParent = btn.Parent as FrameworkElement; + while ((notifBoxParent = notifBoxParent.Parent as FrameworkElement) != null && + !(notifBoxParent is NotificationBox)) ; + } + if (notifBoxParent != null) + { + PhoneApplicationPage page = Page; + if (page != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + grid.Children.Remove(notifBoxParent); + } + + NotifBoxData notifBoxData = notifBoxParent.Tag as NotifBoxData; + notifyBox = notifBoxData.previous as NotificationBox; + callbackId = notifBoxData.callbackId as string; + + if (notifyBox == null) + { + page.BackKeyPress -= page_BackKeyPress; + } + } + + } + DispatchCommandResult(new PluginResult(PluginResult.Status.OK, retVal), callbackId); + } + + + + public void beep(string options) + { + string[] args = JSON.JsonHelper.Deserialize<string[]>(options); + int times = int.Parse(args[0]); + + string resourcePath = BaseCommand.GetBaseURL() + "Plugins/cordova-plugin-dialogs/notification-beep.wav"; + + StreamResourceInfo sri = Application.GetResourceStream(new Uri(resourcePath, UriKind.Relative)); + + if (sri != null) + { + SoundEffect effect = SoundEffect.FromStream(sri.Stream); + SoundEffectInstance inst = effect.CreateInstance(); + ThreadPool.QueueUserWorkItem((o) => + { + // cannot interact with UI !! + do + { + inst.Play(); + Thread.Sleep(effect.Duration + TimeSpan.FromMilliseconds(100)); + } + while (--times > 0); + + }); + + } + + // TODO: may need a listener to trigger DispatchCommandResult after the alarm has finished executing... + DispatchCommandResult(); + } + + // Display an indeterminate progress indicator + public void activityStart(string unused) + { + + Deployment.Current.Dispatcher.BeginInvoke(() => + { + PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; + + if (frame != null) + { + PhoneApplicationPage page = frame.Content as PhoneApplicationPage; + + if (page != null) + { + var temp = page.FindName("LayoutRoot"); + Grid grid = temp as Grid; + if (grid != null) + { + if (progressBar != null) + { + grid.Children.Remove(progressBar); + } + progressBar = new ProgressBar(); + progressBar.IsIndeterminate = true; + progressBar.IsEnabled = true; + + grid.Children.Add(progressBar); + } + } + } + }); + } + + + // Remove our indeterminate progress indicator + public void activityStop(string unused) + { + Deployment.Current.Dispatcher.BeginInvoke(() => + { + if (progressBar != null) + { + progressBar.IsEnabled = false; + PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; + if (frame != null) + { + PhoneApplicationPage page = frame.Content as PhoneApplicationPage; + if (page != null) + { + Grid grid = page.FindName("LayoutRoot") as Grid; + if (grid != null) + { + grid.Children.Remove(progressBar); + } + } + } + progressBar = null; + } + }); + } + + public void vibrate(string vibrateDuration) + { + + int msecs = 200; // set default + + try + { + string[] args = JSON.JsonHelper.Deserialize<string[]>(vibrateDuration); + + msecs = int.Parse(args[0]); + if (msecs < 1) + { + msecs = 1; + } + } + catch (FormatException) + { + + } + + VibrateController.Default.Start(TimeSpan.FromMilliseconds(msecs)); + + // TODO: may need to add listener to trigger DispatchCommandResult when the vibration ends... + DispatchCommandResult(); + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/NotificationBox.xaml b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/NotificationBox.xaml new file mode 100644 index 00000000..2d564fba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/NotificationBox.xaml @@ -0,0 +1,79 @@ +<!-- + 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. +--> +<UserControl x:Class="WPCordovaClassLib.Cordova.UI.NotificationBox" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + mc:Ignorable="d" + FontFamily="{StaticResource PhoneFontFamilyNormal}" + FontSize="{StaticResource PhoneFontSizeNormal}" + Foreground="{StaticResource PhoneForegroundBrush}" + d:DesignHeight="800" d:DesignWidth="480" VerticalAlignment="Stretch"> + + <!--TitlePanel contains the name of the application and page title--> + <Grid x:Name="LayoutRoot" + Background="{StaticResource PhoneSemitransparentBrush}"> + <Grid.RowDefinitions> + <RowDefinition Height="*"></RowDefinition> + </Grid.RowDefinitions> + + <Grid x:Name="TitlePanel" + Grid.Row="0" + VerticalAlignment="Top" + Background="{StaticResource PhoneSemitransparentBrush}"> + <Grid.RowDefinitions> + <RowDefinition Height="Auto"></RowDefinition> + <RowDefinition Height="*"></RowDefinition> + <RowDefinition Height="Auto"></RowDefinition> + </Grid.RowDefinitions> + + <TextBlock x:Name="PageTitle" + Text="Title" + Margin="10,10" + Grid.Row="0" + Style="{StaticResource PhoneTextTitle2Style}"/> + + <ScrollViewer x:Name="ContentScroller" + Grid.Row="1" + MinHeight="120" + Margin="10,10"> + <StackPanel Orientation="Vertical"> + <TextBlock x:Name="SubTitle" + Text="Subtitle" + Width="Auto" + TextWrapping="Wrap" + Style="{StaticResource PhoneTextTitle3Style}"/> + <TextBox x:Name="InputText" + Visibility="Collapsed"/> + </StackPanel> + </ScrollViewer> + + <ScrollViewer HorizontalScrollBarVisibility="Auto" + Grid.Row="2" + VerticalScrollBarVisibility="Disabled"> + <StackPanel x:Name="ButtonPanel" + Margin="10,10" + Orientation="Horizontal"/> + </ScrollViewer> + + </Grid> + </Grid> + +</UserControl> diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/NotificationBox.xaml.cs b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/NotificationBox.xaml.cs new file mode 100644 index 00000000..50b2f2a8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/NotificationBox.xaml.cs @@ -0,0 +1,41 @@ +/* + 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. +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; + +namespace WPCordovaClassLib.Cordova.UI +{ + public partial class NotificationBox : UserControl + { + public NotificationBox() + { + InitializeComponent(); + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/notification-beep.wav b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/notification-beep.wav Binary files differnew file mode 100644 index 00000000..d0ad085f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/src/wp/notification-beep.wav diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/tests/plugin.xml b/StoneIsland/plugins/cordova-plugin-dialogs/tests/plugin.xml new file mode 100644 index 00000000..f021ddd5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/tests/plugin.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="cordova-plugin-dialogs-tests" + version="1.1.1"> + <name>Cordova Notification Plugin Tests</name> + <license>Apache 2.0</license> + + <js-module src="tests.js" name="tests"> + </js-module> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/tests/tests.js b/StoneIsland/plugins/cordova-plugin-dialogs/tests/tests.js new file mode 100644 index 00000000..16e9cd99 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/tests/tests.js @@ -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. + * +*/ + +exports.defineAutoTests = function () { + describe('Notification (navigator.notification)', function () { + it("should exist", function () { + expect(navigator.notification).toBeDefined(); + }); + + it("should contain a beep function", function () { + expect(typeof navigator.notification.beep).toBeDefined(); + expect(typeof navigator.notification.beep).toBe("function"); + }); + + it("should contain an alert function", function () { + expect(typeof navigator.notification.alert).toBeDefined(); + expect(typeof navigator.notification.alert).toBe("function"); + }); + + it("should contain a confirm function", function () { + expect(typeof navigator.notification.confirm).toBeDefined(); + expect(typeof navigator.notification.confirm).toBe("function"); + }); + + it("should contain a prompt function", function () { + expect(typeof navigator.notification.prompt).toBeDefined(); + expect(typeof navigator.notification.prompt).toBe("function"); + }); + }); +}; + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +exports.defineManualTests = function (contentEl, createActionButton) { + var logMessage = function (message) { + var log = document.getElementById('info'); + var logLine = document.createElement('div'); + logLine.innerHTML = message; + log.appendChild(logLine); + } + + var clearLog = function () { + var log = document.getElementById('info'); + log.innerHTML = ''; + } + + var beep = function () { + console.log("beep()"); + navigator.notification.beep(3); + }; + + var alertDialog = function (message, title, button) { + console.log("alertDialog()"); + navigator.notification.alert(message, + function () { + console.log("Alert dismissed."); + }, + title, button); + console.log("After alert"); + }; + + var confirmDialogA = function (message, title, buttons) { + clearLog(); + navigator.notification.confirm(message, + function (r) { + if (r === 0) { + logMessage("Dismissed dialog without making a selection."); + console.log("Dismissed dialog without making a selection."); + } else { + console.log("You selected " + r); + logMessage("You selected " + (buttons.split(","))[r - 1]); + } + }, + title, + buttons); + }; + + var confirmDialogB = function (message, title, buttons) { + clearLog(); + navigator.notification.confirm(message, + function (r) { + if (r === 0) { + logMessage("Dismissed dialog without making a selection."); + console.log("Dismissed dialog without making a selection."); + } else { + console.log("You selected " + r); + logMessage("You selected " + buttons[r - 1]); + } + }, + title, + buttons); + }; + + var promptDialog = function (message, title, buttons) { + clearLog(); + navigator.notification.prompt(message, + function (r) { + if (r && r.buttonIndex === 0) { + var msg = "Dismissed dialog"; + if (r.input1) { + msg += " with input: " + r.input1 + } + logMessage(msg); + console.log(msg); + } else { + console.log("You selected " + r.buttonIndex + " and entered: " + r.input1); + logMessage("You selected " + buttons[r.buttonIndex - 1] + " and entered: " + r.input1); + } + }, + title, + buttons); + }; + + /******************************************************************************/ + + var dialogs_tests = '<div id="beep"></div>' + + 'Expected result: Device will beep (unless device is on silent). Nothing will get updated in status box.' + + '<h2>Dialog Tests</h2>' + + '<h3>Dialog boxes will pop up for each of the following tests</h3>' + + '<p/> <div id="alert"></div>' + + 'Expected result: Dialog will say "You pressed alert". Press continue to close dialog. Nothing will get updated in status box.' + + '<p/> <div id="confirm_deprecated"></div>' + + 'Expected result: Dialog will say "You pressed confirm". Press Yes, No, or Maybe to close dialog. Status box will tell you what option you selected.' + + '<p/> <div id="confirm"></div>' + + 'Expected result: Dialog will say "You pressed confirm". Press Yes, No, or Maybe, Not Sure to close dialog. Status box will tell you what option you selected, and should use 1-based indexing.' + + '<p/> <div id="prompt"></div>' + + 'Expected result: Dialog will say "You pressed prompt". Enter any message and press Yes, No, or Maybe, Not Sure to close dialog. Status box will tell you what option you selected and message you entered, and should use 1-based indexing.' + + '<p/> <div id="built_in_alert"></div>' + + 'Expected result: Dialog will have title "index.html" and say "You pressed alert" Press OK to close dialog. Nothing will get updated in status box.' + + '<p/> <div id="built_in_confirm"></div>' + + 'Expected result: Dialog will have title "index.html" and say "You selected confirm". Press Cancel or OK to close dialog. Nothing will get updated in status box.' + + '<p/> <div id="built_in_prompt"></div>' + + 'Expected result: Dialog will have title "index.html" and say "This is a prompt". "Default value" will be in text box. Press Cancel or OK to close dialog. Nothing will get updated in status box.'; + + contentEl.innerHTML = '<div id="info"></div>' + + dialogs_tests; + + createActionButton('Beep', function () { + beep(); + }, 'beep'); + + createActionButton('Alert Dialog', function () { + alertDialog('You pressed alert.', 'Alert Dialog', 'Continue'); + }, 'alert'); + + // WP8.1 detection is necessary since it doesn't support confirm dialogs with more than 2 buttons + var isRunningOnWP81 = cordova.platformId == "windows" && navigator.userAgent.indexOf('Windows Phone') > -1; + + createActionButton('Confirm Dialog - Deprecated', function () { + var buttons = isRunningOnWP81 ? 'Yes,No' : 'Yes,No,Maybe'; + confirmDialogA('You pressed confirm.', 'Confirm Dialog', buttons); + }, 'confirm_deprecated'); + + createActionButton('Confirm Dialog', function () { + var buttons = isRunningOnWP81 ? ['Yes', 'Actually, No'] : ['Yes', 'No', 'Maybe, Not Sure']; + confirmDialogB('You pressed confirm.', 'Confirm Dialog', buttons); + }, 'confirm'); + + createActionButton('Prompt Dialog', function () { + promptDialog('You pressed prompt.', 'Prompt Dialog', ['Yes', 'No', 'Maybe, Not Sure']); + }, 'prompt'); + + createActionButton('Built-in Alert Dialog', function () { + typeof alert === 'function' && alert('You pressed alert'); + }, 'built_in_alert'); + + createActionButton('Built-in Confirm Dialog', function () { + typeof confirm === 'function' && confirm('You selected confirm'); + }, 'built_in_confirm'); + + createActionButton('Built-in Prompt Dialog', function () { + typeof prompt === 'function' && prompt('This is a prompt', 'Default value'); + }, 'built_in_prompt'); +}; diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/android/notification.js b/StoneIsland/plugins/cordova-plugin-dialogs/www/android/notification.js new file mode 100644 index 00000000..8936a5c2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/android/notification.js @@ -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. + * +*/ + +var exec = require('cordova/exec'); + +/** + * Provides Android enhanced notification API. + */ +module.exports = { + activityStart : function(title, message) { + // If title and message not specified then mimic Android behavior of + // using default strings. + if (typeof title === "undefined" && typeof message == "undefined") { + title = "Busy"; + message = 'Please wait...'; + } + + exec(null, null, 'Notification', 'activityStart', [ title, message ]); + }, + + /** + * Close an activity dialog + */ + activityStop : function() { + exec(null, null, 'Notification', 'activityStop', []); + }, + + /** + * Display a progress dialog with progress bar that goes from 0 to 100. + * + * @param {String} + * title Title of the progress dialog. + * @param {String} + * message Message to display in the dialog. + */ + progressStart : function(title, message) { + exec(null, null, 'Notification', 'progressStart', [ title, message ]); + }, + + /** + * Close the progress dialog. + */ + progressStop : function() { + exec(null, null, 'Notification', 'progressStop', []); + }, + + /** + * Set the progress dialog value. + * + * @param {Number} + * value 0-100 + */ + progressValue : function(value) { + exec(null, null, 'Notification', 'progressValue', [ value ]); + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/blackberry10/beep.js b/StoneIsland/plugins/cordova-plugin-dialogs/www/blackberry10/beep.js new file mode 100644 index 00000000..401049e8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/blackberry10/beep.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. + * +*/ + +module.exports = function (quantity) { + var count = 0, + beepObj, + play = function () { + //create new object every time due to strage playback behaviour + beepObj = new Audio('local:///chrome/plugin/cordova-plugin-dialogs/notification-beep.wav'); + beepObj.addEventListener("ended", callback); + beepObj.play(); + }, + callback = function () { + if (--count > 0) { + play(); + } else { + delete beepObj; + } + }; + count += quantity || 1; + if (count > 0) { + play(); + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/blackberry10/notification-beep.wav b/StoneIsland/plugins/cordova-plugin-dialogs/www/blackberry10/notification-beep.wav Binary files differnew file mode 100644 index 00000000..d0ad085f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/blackberry10/notification-beep.wav diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/browser/notification.js b/StoneIsland/plugins/cordova-plugin-dialogs/www/browser/notification.js new file mode 100644 index 00000000..e8753093 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/browser/notification.js @@ -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. + * +*/ + +// Platform: browser +window.navigator.notification = window.navigator.notification || {}; + +module.exports.alert = window.navigator.notification.alert = function(message, callback) { + // `notification.alert` executes asynchronously + setTimeout(function() { + window.alert(message); + if (callback) { + callback(); + } + }, 0); +}; + + +module.exports.confirm = window.navigator.notification.confirm = function(message, callback) { + // `notification.confirm` executes asynchronously + setTimeout(function() { + var result = window.confirm(message); + if (callback) { + if (result) { + callback(1); // OK + } + else { + callback(2); // Cancel + } + } + }, 0); +}; + + +module.exports.prompt = window.navigator.notification.prompt = function(message, callback, title, buttonLabels, defaultText) { + // `notification.prompt` executes asynchronously + setTimeout(function() { + var result = window.prompt(message, defaultText || ''); + if (callback) { + if (result === null) { + callback({ buttonIndex: 2, input1: '' }); // Cancel + } + else { + callback({ buttonIndex: 1, input1: result }); // OK + } + } + }, 0); +}; + + +module.exports.beep = window.navigator.notification.beep = function(times) { + if (times > 0) { + var BEEP_DURATION = 700; + var BEEP_INTERVAL = 300; + + if (audioContext) { + // Start a beep, using the Audio API + var osc = audioContext.createOscillator(); + osc.type = 0; // sounds like a "beep" + osc.connect(audioContext.destination); + osc.start(0); + + setTimeout(function() { + // Stop the beep after the BEEP_DURATION + osc.stop(0); + + if (--times > 0) { + // Beep again, after a pause + setTimeout(function() { + navigator.notification.beep(times); + }, BEEP_INTERVAL); + } + + }, BEEP_DURATION); + } + else if (typeof(console) !== 'undefined' && typeof(console.log) === 'function') { + // Audio API isn't supported, so just write `beep` to the console + for (var i = 0; i < times; i++) { + console.log('Beep!'); + } + } + } +}; + +var audioContext = (function() { + // Determine if the Audio API is supported by this browser + var AudioApi = window.AudioContext; + if (!AudioApi) { + AudioApi = window.webkitAudioContext; + } + + if (AudioApi) { + // The Audio API is supported, so create a singleton instance of the AudioContext + return new AudioApi(); + } + + return undefined; +}()); diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/danger-press.png b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/danger-press.png Binary files differnew file mode 100644 index 00000000..d7529b5b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/danger-press.png diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/danger.png b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/danger.png Binary files differnew file mode 100644 index 00000000..400e3ae3 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/danger.png diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/default.png b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/default.png Binary files differnew file mode 100644 index 00000000..2ff298a1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/default.png diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/gradient.png b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/gradient.png Binary files differnew file mode 100644 index 00000000..b2885450 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/gradient.png diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/notification.css b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/notification.css new file mode 100644 index 00000000..34d92b88 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/notification.css @@ -0,0 +1,248 @@ +/* + * + * 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 dialog setup */ +form[role="dialog"] { + background: + url(../img/pattern.png) repeat left top, + url(../img/gradient.png) no-repeat left top / 100% 100%; + overflow: hidden; + position: absolute; + z-index: 100; + top: 0; + left: 0; + right: 0; + bottom: 0; + padding: 1.5rem 0 7rem; + font-family: "MozTT", Sans-serif; + font-size: 0; + /* Using font-size: 0; we avoid the unwanted visual space (about 3px) + created by white-spaces and break lines in the code betewen inline-block elements */ + color: #fff; + text-align: left; +} + +form[role="dialog"]:before { + content: ""; + display: inline-block; + vertical-align: middle; + width: 0.1rem; + height: 100%; + margin-left: -0.1rem; +} + +form[role="dialog"] > section { + font-weight: lighter; + font-size: 1.8rem; + color: #FAFAFA; + padding: 0 1.5rem; + -moz-box-sizing: padding-box; + width: 100%; + display: inline-block; + overflow-y: scroll; + max-height: 100%; + vertical-align: middle; + white-space: normal; +} + +form[role="dialog"] h1 { + font-weight: normal; + font-size: 1.6rem; + line-height: 1.5em; + color: #fff; + margin: 0; + padding: 0 1.5rem 1rem; + border-bottom: 0.1rem solid #686868; +} + +/* Menu & buttons setup */ +form[role="dialog"] menu { + margin: 0; + padding: 1.5rem; + padding-bottom: 0.5rem; + border-top: solid 0.1rem rgba(255, 255, 255, 0.1); + background: #2d2d2d url(../img/pattern.png) repeat left top; + display: block; + overflow: hidden; + position: absolute; + left: 0; + right: 0; + bottom: 0; + text-align: center; +} + +form[role="dialog"] menu button::-moz-focus-inner { + border: none; + outline: none; +} +form[role="dialog"] menu button { + width: 100%; + height: 2.4rem; + margin: 0 0 1rem; + padding: 0 1.5rem; + -moz-box-sizing: border-box; + display: inline-block; + vertical-align: middle; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + background: #fafafa url(../img/default.png) repeat-x left bottom/ auto 100%; + border: 0.1rem solid #a6a6a6; + border-radius: 0.3rem; + font: 500 1.2rem/2.4rem 'MozTT', Sans-serif; + color: #333; + text-align: center; + text-shadow: 0.1rem 0.1rem 0 rgba(255,255,255,0.3); + text-decoration: none; + outline: none; +} + +/* Press (default & recommend) */ +form[role="dialog"] menu button:active, +form[role="dialog"] menu button.recommend:active, +a.recommend[role="button"]:active { + border-color: #008aaa; + color: #333; +} + +/* Recommend */ +form[role="dialog"] menu button.recommend { + background-image: url(../img/recommend.png); + background-color: #00caf2; + border-color: #008eab; +} + +/* Danger */ +form[role="dialog"] menu button.danger, +a.danger[role="button"] { + background-image: url(../img/danger.png); + background-color: #b70404; + color: #fff; + text-shadow: none; + border-color: #820000; +} + +/* Danger Press */ +form[role="dialog"] menu button.danger:active { + background-image: url(../img/danger-press.png); + background-color: #890707; +} + +/* Disabled */ +form[role="dialog"] > menu > button[disabled] { + background: #5f5f5f; + color: #4d4d4d; + text-shadow: none; + border-color: #4d4d4d; + pointer-events: none; +} + + +form[role="dialog"] menu button:nth-child(even) { + margin-left: 1rem; +} + +form[role="dialog"] menu button, +form[role="dialog"] menu button:nth-child(odd) { + margin: 0 0 1rem 0; +} + +form[role="dialog"] menu button { + width: calc((100% - 1rem) / 2); +} + +form[role="dialog"] menu button.full { + width: 100%; +} + +/* Specific component code */ +form[role="dialog"] p { + word-wrap: break-word; + margin: 1rem 0 0; + padding: 0 1.5rem 1rem; + line-height: 3rem; +} + +form[role="dialog"] p img { + float: left; + margin-right: 2rem; +} + +form[role="dialog"] p strong { + font-weight: lighter; +} + +form[role="dialog"] p small { + font-size: 1.4rem; + font-weight: normal; + color: #cbcbcb; + display: block; +} + +form[role="dialog"] dl { + border-top: 0.1rem solid #686868; + margin: 1rem 0 0; + overflow: hidden; + padding-top: 1rem; + font-size: 1.6rem; + line-height: 2.2rem; +} + +form[role="dialog"] dl > dt { + clear: both; + float: left; + width: 7rem; + padding-left: 1.5rem; + font-weight: 500; + text-align: left; +} + +form[role="dialog"] dl > dd { + padding-right: 1.5rem; + font-weight: 300; + text-overflow: ellipsis; + vertical-align: top; + overflow: hidden; +} + +/* input areas */ +input[type="text"], +input[type="password"], +input[type="email"], +input[type="tel"], +input[type="search"], +input[type="url"], +input[type="number"], +textarea { + -moz-box-sizing: border-box; + display: block; + overflow: hidden; + width: 100%; + height: 3rem; + resize: none; + padding: 0 1rem; + font-size: 1.6rem; + line-height: 3rem; + border: 0.1rem solid #ccc; + border-radius: 0.3rem; + box-shadow: none; /* override the box-shadow from the system (performance issue) */ + background: #fff url(input_areas/images/ui/shadow.png) repeat-x; +} diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/pattern.png b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/pattern.png Binary files differnew file mode 100644 index 00000000..af03f569 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/pattern.png diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/recommend.png b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/recommend.png Binary files differnew file mode 100644 index 00000000..42aed390 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/firefoxos/recommend.png diff --git a/StoneIsland/plugins/cordova-plugin-dialogs/www/notification.js b/StoneIsland/plugins/cordova-plugin-dialogs/www/notification.js new file mode 100644 index 00000000..c3f70d07 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-dialogs/www/notification.js @@ -0,0 +1,112 @@ +/* + * + * 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 platform = require('cordova/platform'); + +/** + * Provides access to notifications on the device. + */ + +module.exports = { + + /** + * Open a native alert dialog, with a customizable title and button text. + * + * @param {String} message Message to print in the body of the alert + * @param {Function} completeCallback The callback that is called when user clicks on a button. + * @param {String} title Title of the alert dialog (default: Alert) + * @param {String} buttonLabel Label of the close button (default: OK) + */ + alert: function(message, completeCallback, title, buttonLabel) { + var _title = (title || "Alert"); + var _buttonLabel = (buttonLabel || "OK"); + exec(completeCallback, null, "Notification", "alert", [message, _title, _buttonLabel]); + }, + + /** + * Open a native confirm dialog, with a customizable title and button text. + * The result that the user selects is returned to the result callback. + * + * @param {String} message Message to print in the body of the alert + * @param {Function} resultCallback The callback that is called when user clicks on a button. + * @param {String} title Title of the alert dialog (default: Confirm) + * @param {Array} buttonLabels Array of the labels of the buttons (default: ['OK', 'Cancel']) + */ + confirm: function(message, resultCallback, title, buttonLabels) { + var _title = (title || "Confirm"); + var _buttonLabels = (buttonLabels || ["OK", "Cancel"]); + + // Strings are deprecated! + if (typeof _buttonLabels === 'string') { + console.log("Notification.confirm(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array)."); + } + + // Some platforms take an array of button label names. + // Other platforms take a comma separated list. + // For compatibility, we convert to the desired type based on the platform. + if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" || + platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu" || + platform.id == "windows8" || platform.id == "windows") { + + if (typeof _buttonLabels === 'string') { + _buttonLabels = _buttonLabels.split(","); // not crazy about changing the var type here + } + } else { + if (Array.isArray(_buttonLabels)) { + var buttonLabelArray = _buttonLabels; + _buttonLabels = buttonLabelArray.toString(); + } + } + exec(resultCallback, null, "Notification", "confirm", [message, _title, _buttonLabels]); + }, + + /** + * Open a native prompt dialog, with a customizable title and button text. + * The following results are returned to the result callback: + * buttonIndex Index number of the button selected. + * input1 The text entered in the prompt dialog box. + * + * @param {String} message Dialog message to display (default: "Prompt message") + * @param {Function} resultCallback The callback that is called when user clicks on a button. + * @param {String} title Title of the dialog (default: "Prompt") + * @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"]) + * @param {String} defaultText Textbox input value (default: empty string) + */ + prompt: function(message, resultCallback, title, buttonLabels, defaultText) { + var _message = (message || "Prompt message"); + var _title = (title || "Prompt"); + var _buttonLabels = (buttonLabels || ["OK","Cancel"]); + var _defaultText = (defaultText || ""); + exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]); + }, + + /** + * Causes the device to beep. + * On Android, the default notification ringtone is played "count" times. + * + * @param {Integer} count The number of beeps. + */ + beep: function(count) { + var defaultedCount = count || 1; + exec(null, null, "Notification", "beep", [ defaultedCount ]); + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-geolocation/CONTRIBUTING.md new file mode 100644 index 00000000..f7dbcaba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/LICENSE b/StoneIsland/plugins/cordova-plugin-geolocation/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/NOTICE b/StoneIsland/plugins/cordova-plugin-geolocation/NOTICE new file mode 100644 index 00000000..8ec56a52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/README.md new file mode 100644 index 00000000..eb10b9f8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/README.md @@ -0,0 +1,293 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +This plugin provides information about the device's location, such as +latitude and longitude. Common sources of location information include +Global Positioning System (GPS) and location inferred from network +signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, +and GSM/CDMA cell IDs. There is no guarantee that the API returns the +device's actual location. + +This API is based on the +[W3C Geolocation API Specification](http://dev.w3.org/geo/api/spec-source.html), +and only executes on devices that don't already provide an implementation. + +__WARNING__: Collection and use of geolocation data +raises important privacy issues. Your app's privacy policy should +discuss how the app uses geolocation data, whether it is shared with +any other parties, and the level of precision of the data (for +example, coarse, fine, ZIP code level, etc.). Geolocation data is +generally considered sensitive because it can reveal user's +whereabouts and, if stored, the history of their travels. +Therefore, in addition to the app's privacy policy, you should +strongly consider providing a just-in-time notice before the app +accesses geolocation data (if the device operating system doesn't do +so already). That notice should provide the same information noted +above, as well as obtaining the user's permission (e.g., by presenting +choices for __OK__ and __No Thanks__). For more information, please +see the Privacy Guide. + +This plugin defines a global `navigator.geolocation` object (for platforms +where it is otherwise missing). + +Although the object is in the global scope, features provided by this plugin +are not available until after the `deviceready` event. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + +## Installation + +This requires cordova 5.0+ ( current stable 1.0.0 ) + + cordova plugin add cordova-plugin-geolocation + +Older versions of cordova can still install via the deprecated id ( stale 0.3.12 ) + + cordova plugin add org.apache.cordova.geolocation + +It is also possible to install via repo url directly ( unstable ) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + +## Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Firefox OS +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows 8 +- Windows + +## Methods + +- navigator.geolocation.getCurrentPosition +- navigator.geolocation.watchPosition +- navigator.geolocation.clearWatch + +## Objects (Read-Only) + +- Position +- PositionError +- Coordinates + +## navigator.geolocation.getCurrentPosition + +Returns the device's current position to the `geolocationSuccess` +callback with a `Position` object as the parameter. If there is an +error, the `geolocationError` callback is passed a +`PositionError` object. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + +### Parameters + +- __geolocationSuccess__: The callback that is passed the current position. + +- __geolocationError__: _(Optional)_ The callback that executes if an error occurs. + +- __geolocationOptions__: _(Optional)_ The geolocation options. + + +### Example + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + +## navigator.geolocation.watchPosition + +Returns the device's current position when a change in position is detected. +When the device retrieves a new location, the `geolocationSuccess` +callback executes with a `Position` object as the parameter. If +there is an error, the `geolocationError` callback executes with a +`PositionError` object as the parameter. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + +### Parameters + +- __geolocationSuccess__: The callback that is passed the current position. + +- __geolocationError__: (Optional) The callback that executes if an error occurs. + +- __geolocationOptions__: (Optional) The geolocation options. + +### Returns + +- __String__: returns a watch id that references the watch position interval. The watch id should be used with `navigator.geolocation.clearWatch` to stop watching for changes in position. + +### Example + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Optional parameters to customize the retrieval of the geolocation +`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + +### Options + +- __enableHighAccuracy__: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a `Position` using network-based methods. Setting this property to `true` tells the framework to use more accurate methods, such as satellite positioning. _(Boolean)_ + +- __timeout__: The maximum length of time (milliseconds) that is allowed to pass from the call to `navigator.geolocation.getCurrentPosition` or `geolocation.watchPosition` until the corresponding `geolocationSuccess` callback executes. If the `geolocationSuccess` callback is not invoked within this time, the `geolocationError` callback is passed a `PositionError.TIMEOUT` error code. (Note that when used in conjunction with `geolocation.watchPosition`, the `geolocationError` callback could be called on an interval every `timeout` milliseconds!) _(Number)_ + +- __maximumAge__: Accept a cached position whose age is no greater than the specified time in milliseconds. _(Number)_ + +### Android Quirks + +Android 2.x emulators do not return a geolocation result unless the `enableHighAccuracy` option is set to `true`. + +## navigator.geolocation.clearWatch + +Stop watching for changes to the device's location referenced by the +`watchID` parameter. + + navigator.geolocation.clearWatch(watchID); + +### Parameters + +- __watchID__: The id of the `watchPosition` interval to clear. (String) + +### Example + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + +## Position + +Contains `Position` coordinates and timestamp, created by the geolocation API. + +### Properties + +- __coords__: A set of geographic coordinates. _(Coordinates)_ + +- __timestamp__: Creation timestamp for `coords`. _(Date)_ + +## Coordinates + +A `Coordinates` object is attached to a `Position` object that is +available to callback functions in requests for the current position. +It contains a set of properties that describe the geographic coordinates of a position. + +### Properties + +* __latitude__: Latitude in decimal degrees. _(Number)_ + +* __longitude__: Longitude in decimal degrees. _(Number)_ + +* __altitude__: Height of the position in meters above the ellipsoid. _(Number)_ + +* __accuracy__: Accuracy level of the latitude and longitude coordinates in meters. _(Number)_ + +* __altitudeAccuracy__: Accuracy level of the altitude coordinate in meters. _(Number)_ + +* __heading__: Direction of travel, specified in degrees counting clockwise relative to the true north. _(Number)_ + +* __speed__: Current ground speed of the device, specified in meters per second. _(Number)_ + +### Amazon Fire OS Quirks + +__altitudeAccuracy__: Not supported by Android devices, returning `null`. + +### Android Quirks + +__altitudeAccuracy__: Not supported by Android devices, returning `null`. + +## PositionError + +The `PositionError` object is passed to the `geolocationError` +callback function when an error occurs with navigator.geolocation. + +### Properties + +- __code__: One of the predefined error codes listed below. + +- __message__: Error message describing the details of the error encountered. + +### Constants + +- `PositionError.PERMISSION_DENIED` + - Returned when users do not allow the app to retrieve position information. This is dependent on the platform. +- `PositionError.POSITION_UNAVAILABLE` + - Returned when the device is unable to retrieve a position. In general, this means the device is not connected to a network or can't get a satellite fix. +- `PositionError.TIMEOUT` + - Returned when the device is unable to retrieve a position within the time specified by the `timeout` included in `geolocationOptions`. When used with `navigator.geolocation.watchPosition`, this error could be repeatedly passed to the `geolocationError` callback every `timeout` milliseconds. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-geolocation/RELEASENOTES.md new file mode 100644 index 00000000..197b28e5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/RELEASENOTES.md @@ -0,0 +1,129 @@ +<!-- +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +--> +# Release Notes + +### 0.3.0 (Sept 5, 2013) +* Added support for windows 8 (Adds required permission) + +### 0.3.2 (Sept 25, 2013) +* CB-4889 bumping&resetting version +* [BlackBerry10] removed uneeded permission tags in plugin.xml +* CB-4889 renaming org.apache.cordova.core.geolocation to org.apache.cordova.geolocation + +### 0.3.3 (Oct 28, 2013) +* CB-5128: add repo + issue tag to plugin.xml for geolocation plugin +* [CB-4915] Incremented plugin version on dev branch. + +### 0.3.4 (Dec 4, 2013) +* Append proxy to platform definition in plugin.xml +* Append windows 8 Geolocation proxy +* Code clean-up for android src. +* Updated amazon-fireos platform + reverting some of the fixes in android code. +* Added amazon-fireos platform + some of the fixes in android code. +* CB-5334 [BlackBerry10] Use command proxy +* call FxOS's getCurrentProxy added +* pass by only coords +* proper implementation for firefoxos + +### 0.3.5 (Jan 02, 2014) +* CB-5658 Add doc/index.md for Geolocation plugin +* windows8: adds missing reference to PositionError (w/o it the app crashes) +* Removing incorrectly added closing comments for wp7 platform in plugin.xml + +### 0.3.6 (Feb 05, 2014) +* add ubuntu platform support +* CB-5326 adding FFOS permission and updating supported platforms +* CB-5729 [BlackBerry10] Update GeolocationProxy to return collapsed object + +### 0.3.7 (Apr 17, 2014) +* CB-6422: [windows8] use cordova/exec/proxy +* CB-6212: [iOS] fix warnings compiled under arm64 64-bit +* CB-5977: [android] Removing the Android Geolocation Code. Mission Accomplished. +* CB-6460: Update license headers +* Add NOTICE file + +### 0.3.8 (Jun 05, 2014) +* CB-6127 Spanish and French Translations added. Github close #14 +* CB-6804 Add license +* CB-5416 - Adding support for auto-managing permissions +* CB-6491 add CONTRIBUTING.md +* pass by only coords +* proper implementation for firefoxos +* call FxOS's getCurrentProxy added + +### 0.3.9 (Aug 06, 2014) +* **FFOS** update GeolocationProxy.js +* CB-7187 ios: Add explicit dependency on CoreLocation.framework +* CB-7187 Delete unused #import of CDVShared.h +* CB-6127 Updated translations for docs +* ios: Changed distanceFilter from none to 5 meters, prevents it from spamming the callback even though nothing changed. + + +### 0.3.10 (Sep 17, 2014) +* CB-7556 iOS: Clearing all Watches does not stop Location Services +* CB-7158 Fix geolocation for ios 8 +* Revert CB-6911 partially (keeping Info.plist key installation for iOS 8) +* CB-6911 Geolocation fails in iOS 8 +* CB-5114 Windows 8.1 - Use a new proxy as old geolocation methods is deprecated +* CB-5114 Append Windows 8.1 into plugin.xml + Optimize Windows 8 Geolocation proxy +* Renamed test dir, added nested plugin.xml +* added documentation for manual tests +* CB-7146 Added manual tests +* Removed js-module for tests from plugin.xml +* Changing cdvtest format to use module exports +* register tests using new style +* Convert tests to new style +* Removed amazon-fireos code for geolocation. +* CB-7571 Bump version of nested plugin to match parent plugin + +### 0.3.11 (Dec 02, 2014) +* Do not stop updating location when the error is `kCLErrorLocationUnknown` +* CB-8094 Pended auto tests for **Windows** Store since they require user interaction +* CB-8085 Fix geolocation plugin on **Windows** +* CB-7977 Mention `deviceready` in plugin docs +* CB-7700 cordova-plugin-geolocation documentation translation: cordova-plugin-geolocation + +### 0.3.12 (Feb 04, 2015) +* CB-8351 ios: Use argumentForIndex rather than NSArray extension + +### 1.0.0 (Apr 15, 2015) +* CB-8746 gave plugin major version bump +* CB-8683 changed plugin-id to pacakge-name +* CB-8653 properly updated translated docs to use new id +* CB-8653 updated translated docs to use new id +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* CB-8681 Fixed occasional test failures +* docs: added Windows to supported platforms +* CB-8653 Updated Readme +* CB-8659: ios: 4.0.x Compatibility: Remove use of initWebView method +* CB-8659: ios: 4.0.x Compatibility: Remove use of deprecated headers +* Wrong parameter in Firefox OS plugin +* CB-8568 Integrate TravisCI +* CB-8438 cordova-plugin-geolocation documentation translation: cordova-plugin-geolocation +* CB-8538 Added package.json file +* CB-8443 Geolocation tests fail on Windows due to done is called multiple times + +### 1.0.1 (Jun 17, 2015) +* CB-9128 cordova-plugin-geolocation documentation translation: cordova-plugin-geolocation +* fix npm md issue +* CB-8845 Updated comment why Android tests are currently pended +* CB-8845 Pended tests for Android +* Add more install text for legacy versions of cordova tools. This closes #36 diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/de/README.md new file mode 100644 index 00000000..9cf693e5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/de/README.md @@ -0,0 +1,268 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Dieses Plugin bietet Informationen über das Gerät an den Speicherort, z. B. breiten- und Längengrad. Gemeinsame Quellen von Standortinformationen sind Global Positioning System (GPS) und Lage von Netzwerk-Signale wie IP-Adresse, RFID, WLAN und Bluetooth MAC-Adressen und GSM/CDMA Zelle IDs abgeleitet. Es gibt keine Garantie, dass die API des Geräts tatsächliche Position zurückgibt. + +Diese API basiert auf der [W3C Geolocation API-Spezifikation](http://dev.w3.org/geo/api/spec-source.html), und nur auf Geräten, die nicht bereits eine Implementierung bieten führt. + +**Warnung**: Erhebung und Nutzung von Geolocation-Daten wichtige Privatsphäre wirft. Wie die app benutzt Geolocation-Daten, Ihre app-Datenschutzrichtlinien zu diskutieren, ob es mit allen anderen Parteien und das Niveau der Genauigkeit der Daten (z. B. grob, fein, Postleitzahl, etc..) freigegeben ist. Geolocation-Daten gilt allgemein als empfindlich, weil es den Aufenthaltsort des Benutzers erkennen lässt und wenn gespeichert, die Geschichte von ihren Reisen. Daher neben der app-Privacy Policy sollten stark Sie Bereitstellung einer just-in-Time-Bekanntmachung, bevor die app Geolocation-Daten zugreift (wenn das Betriebssystem des Geräts bereits tun nicht). Diese Benachrichtigung sollte der gleichen Informationen, die vorstehend, sowie die Zustimmung des Benutzers (z.B. durch Präsentation Entscheidungen für das **OK** und **Nein danke**). Weitere Informationen finden Sie in der Datenschutz-Guide. + +Dieses Plugin definiert eine globale `navigator.geolocation`-Objekt (für Plattformen, bei denen es sonst fehlt). + +Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installation + +Dies erfordert Cordova 5.0 + (aktuelle stabile 1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +Ältere Versionen von Cordova können noch über die veraltete Id (veraltete 0.3.12) installieren. + + cordova plugin add org.apache.cordova.geolocation + + +Es ist auch möglich, über Repo Url direkt zu installieren (unstable) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + * Windows + +## Methoden + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Objekte (schreibgeschützt) + + * Position + * Positionsfehler + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Gibt das Gerät aktuelle Position an den `geolocationSuccess`-Rückruf mit einem `Position`-Objekt als Parameter zurück. Wenn ein Fehler vorliegt, wird der Rückruf `geolocationError` ein `PositionError`-Objekt übergeben. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + + * **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + + * **GeolocationError**: *(Optional)* der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + + * **GeolocationOptions**: *(Optional)* die Geolocation-Optionen. + +### Beispiel + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Gibt das Gerät aktuelle Position zurück, wenn eine Änderung erkannt wird. Wenn das Gerät einen neuen Speicherort abgerufen hat, führt der `geolocationSuccess`-Rückruf mit einer `Position`-Objekt als Parameter. Wenn ein Fehler vorliegt, führt der `geolocationError`-Rückruf mit einem `PositionError`-Objekt als Parameter. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + + * **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + + * **GeolocationError**: (Optional) der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + + * **GeolocationOptions**: (Optional) die Geolocation-Optionen. + +### Gibt + + * **String**: gibt eine Uhr-Id, die das Uhr Position Intervall verweist zurück. Die Uhr-Id sollte verwendet werden, mit `navigator.geolocation.clearWatch` , gerade für Änderungen zu stoppen. + +### Beispiel + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Optionalen Parametern, um das Abrufen von Geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Optionen + + * **EnableHighAccuracy**: stellt einen Hinweis, dass die Anwendung die bestmöglichen Ergebnisse benötigt. Standardmäßig versucht das Gerät abzurufen ein `Position` mit netzwerkbasierte Methoden. Wenn diese Eigenschaft auf `true` erzählt den Rahmenbedingungen genauere Methoden, z. B. Satellitenortung verwenden. *(Boolean)* + + * **Timeout**: die maximale Länge der Zeit (in Millisekunden), die zulässig ist, übergeben Sie den Aufruf von `navigator.geolocation.getCurrentPosition` oder `geolocation.watchPosition` bis zu den entsprechenden `geolocationSuccess` Rückruf führt. Wenn die `geolocationSuccess` Rückruf wird nicht aufgerufen, in dieser Zeit die `geolocationError` Rückruf wird übergeben ein `PositionError.TIMEOUT` Fehlercode. (Beachten Sie, dass in Verbindung mit `geolocation.watchPosition` , die `geolocationError` Rückruf könnte auf ein Intervall aufgerufen werden alle `timeout` Millisekunden!) *(Anzahl)* + + * **MaximumAge**: eine zwischengespeicherte Position, deren Alter nicht größer als die angegebene Zeit in Millisekunden ist, zu akzeptieren. *(Anzahl)* + +### Android Eigenarten + +Android 2.x-Emulatoren geben ein Geolocation-Ergebnis nicht zurück, es sei denn, die `EnableHighAccuracy`-Option auf `true` festgelegt ist. + +## navigator.geolocation.clearWatch + +Stoppen Sie, gerade für Änderungen an dem Gerät Speicherort verweist mithilfe des Parameters `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parameter + + * **WatchID**: die Id der `watchPosition` Intervall löschen. (String) + +### Beispiel + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Enthält `Position` koordinaten und Timestamp, erstellt von der Geolocation API. + +### Eigenschaften + + * **coords**: eine Reihe von geographischen Koordinaten. *(Coordinates)* + + * **timestamp**: Zeitstempel der Erstellung für `coords` . *(Date)* + +## Coordinates + +Ein `Coordinates`-Objekt ist ein `Position`-Objekt zugeordnet, die Callback-Funktionen in Anforderungen für die aktuelle Position zur Verfügung steht. Es enthält eine Reihe von Eigenschaften, die die geographischen Koordinaten von einer Position zu beschreiben. + +### Eigenschaften + + * **latitude**: Latitude in Dezimalgrad. *(Anzahl)* + + * **longitude**: Länge in Dezimalgrad. *(Anzahl)* + + * **altitude**: Höhe der Position in Meter über dem Ellipsoid. *(Anzahl)* + + * **accuracy**: Genauigkeit der breiten- und Längengrad Koordinaten in Metern. *(Anzahl)* + + * **AltitudeAccuracy**: Genauigkeit der Koordinate Höhe in Metern. *(Anzahl)* + + * **heading**: Fahrtrichtung, angegeben in Grad relativ zu den Norden im Uhrzeigersinn gezählt. *(Anzahl)* + + * **speed**: aktuelle Geschwindigkeit über Grund des Geräts, in Metern pro Sekunde angegeben. *(Anzahl)* + +### Amazon Fire OS Macken + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +### Android Eigenarten + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +## Positionsfehler + +Das `PositionError`-Objekt wird an die `geolocationError`-Callback-Funktion übergeben, tritt ein Fehler mit navigator.geolocation. + +### Eigenschaften + + * **Code**: einer der vordefinierten Fehlercodes aufgeführt. + + * **Nachricht**: Fehlermeldung, die die Informationen über den aufgetretenen Fehler beschreibt. + +### Konstanten + + * `PositionError.PERMISSION_DENIED` + * Zurückgegeben, wenn Benutzer erlauben nicht die app Positionsinformationen abgerufen werden. Dies ist abhängig von der Plattform. + * `PositionError.POSITION_UNAVAILABLE` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position abzurufen ist. Im Allgemeinen bedeutet dies, dass das Gerät nicht mit einem Netzwerk verbunden ist oder ein Satelliten-Update kann nicht abgerufen werden. + * `PositionError.TIMEOUT` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position innerhalb der festgelegten Zeit abzurufen ist die `timeout` enthalten `geolocationOptions` . Bei Verwendung mit `navigator.geolocation.watchPosition` , könnte dieser Fehler wiederholt übergeben werden, zu der `geolocationError` Rückruf jedes `timeout` Millisekunden.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/de/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/de/index.md new file mode 100644 index 00000000..3fe4e4a8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/de/index.md @@ -0,0 +1,255 @@ +<!--- + 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-plugin-geolocation + +Dieses Plugin bietet Informationen über das Gerät an den Speicherort, z. B. breiten- und Längengrad. Gemeinsame Quellen von Standortinformationen sind Global Positioning System (GPS) und Lage von Netzwerk-Signale wie IP-Adresse, RFID, WLAN und Bluetooth MAC-Adressen und GSM/CDMA Zelle IDs abgeleitet. Es gibt keine Garantie, dass die API des Geräts tatsächliche Position zurückgibt. + +Diese API basiert auf der [W3C Geolocation API-Spezifikation][1], und nur auf Geräten, die nicht bereits eine Implementierung bieten führt. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Warnung**: Erhebung und Nutzung von Geolocation-Daten wichtige Privatsphäre wirft. Wie die app benutzt Geolocation-Daten, Ihre app-Datenschutzrichtlinien zu diskutieren, ob es mit allen anderen Parteien und das Niveau der Genauigkeit der Daten (z. B. grob, fein, Postleitzahl, etc..) freigegeben ist. Geolocation-Daten gilt allgemein als empfindlich, weil es den Aufenthaltsort des Benutzers erkennen lässt und wenn gespeichert, die Geschichte von ihren Reisen. Daher neben der app-Privacy Policy sollten stark Sie Bereitstellung einer just-in-Time-Bekanntmachung, bevor die app Geolocation-Daten zugreift (wenn das Betriebssystem des Geräts bereits tun nicht). Diese Benachrichtigung sollte der gleichen Informationen, die vorstehend, sowie die Zustimmung des Benutzers (z.B. durch Präsentation Entscheidungen für das **OK** und **Nein danke**). Weitere Informationen finden Sie in der Datenschutz-Guide. + +Dieses Plugin definiert eine globale `navigator.geolocation`-Objekt (für Plattformen, bei denen es sonst fehlt). + +Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installation + + cordova plugin add cordova-plugin-geolocation + + +## Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +## Methoden + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Objekte (schreibgeschützt) + +* Position +* Positionsfehler +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Gibt das Gerät aktuelle Position an den `geolocationSuccess`-Rückruf mit einem `Position`-Objekt als Parameter zurück. Wenn ein Fehler vorliegt, wird der Rückruf `geolocationError` ein `PositionError`-Objekt übergeben. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + +* **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + +* **GeolocationError**: *(Optional)* der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + +* **GeolocationOptions**: *(Optional)* die Geolocation-Optionen. + +### Beispiel + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Gibt das Gerät aktuelle Position zurück, wenn eine Änderung erkannt wird. Wenn das Gerät einen neuen Speicherort abgerufen hat, führt der `geolocationSuccess`-Rückruf mit einer `Position`-Objekt als Parameter. Wenn ein Fehler vorliegt, führt der `geolocationError`-Rückruf mit einem `PositionError`-Objekt als Parameter. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + +* **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + +* **GeolocationError**: (Optional) der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + +* **GeolocationOptions**: (Optional) die Geolocation-Optionen. + +### Gibt + +* **String**: gibt eine Uhr-Id, die das Uhr Position Intervall verweist zurück. Die Uhr-Id sollte verwendet werden, mit `navigator.geolocation.clearWatch` , gerade für Änderungen zu stoppen. + +### Beispiel + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Optionalen Parametern, um das Abrufen von Geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Optionen + +* **EnableHighAccuracy**: stellt einen Hinweis, dass die Anwendung die bestmöglichen Ergebnisse benötigt. Standardmäßig versucht das Gerät abzurufen ein `Position` mit netzwerkbasierte Methoden. Wenn diese Eigenschaft auf `true` erzählt den Rahmenbedingungen genauere Methoden, z. B. Satellitenortung verwenden. *(Boolean)* + +* **Timeout**: die maximale Länge der Zeit (in Millisekunden), die zulässig ist, übergeben Sie den Aufruf von `navigator.geolocation.getCurrentPosition` oder `geolocation.watchPosition` bis zu den entsprechenden `geolocationSuccess` Rückruf führt. Wenn die `geolocationSuccess` Rückruf wird nicht aufgerufen, in dieser Zeit die `geolocationError` Rückruf wird übergeben ein `PositionError.TIMEOUT` Fehlercode. (Beachten Sie, dass in Verbindung mit `geolocation.watchPosition` , die `geolocationError` Rückruf könnte auf ein Intervall aufgerufen werden alle `timeout` Millisekunden!) *(Anzahl)* + +* **MaximumAge**: eine zwischengespeicherte Position, deren Alter nicht größer als die angegebene Zeit in Millisekunden ist, zu akzeptieren. *(Anzahl)* + +### Android Eigenarten + +Android 2.x-Emulatoren geben ein Geolocation-Ergebnis nicht zurück, es sei denn, die `EnableHighAccuracy`-Option auf `true` festgelegt ist. + +## navigator.geolocation.clearWatch + +Stoppen Sie, gerade für Änderungen an dem Gerät Speicherort verweist mithilfe des Parameters `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parameter + +* **WatchID**: die Id der `watchPosition` Intervall löschen. (String) + +### Beispiel + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Enthält `Position` koordinaten und Timestamp, erstellt von der Geolocation API. + +### Eigenschaften + +* **coords**: eine Reihe von geographischen Koordinaten. *(Coordinates)* + +* **timestamp**: Zeitstempel der Erstellung für `coords` . *(Date)* + +## Coordinates + +Ein `Coordinates`-Objekt ist ein `Position`-Objekt zugeordnet, die Callback-Funktionen in Anforderungen für die aktuelle Position zur Verfügung steht. Es enthält eine Reihe von Eigenschaften, die die geographischen Koordinaten von einer Position zu beschreiben. + +### Eigenschaften + +* **latitude**: Latitude in Dezimalgrad. *(Anzahl)* + +* **longitude**: Länge in Dezimalgrad. *(Anzahl)* + +* **altitude**: Höhe der Position in Meter über dem Ellipsoid. *(Anzahl)* + +* **accuracy**: Genauigkeit der breiten- und Längengrad Koordinaten in Metern. *(Anzahl)* + +* **AltitudeAccuracy**: Genauigkeit der Koordinate Höhe in Metern. *(Anzahl)* + +* **heading**: Fahrtrichtung, angegeben in Grad relativ zu den Norden im Uhrzeigersinn gezählt. *(Anzahl)* + +* **speed**: aktuelle Geschwindigkeit über Grund des Geräts, in Metern pro Sekunde angegeben. *(Anzahl)* + +### Amazon Fire OS Macken + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +### Android Eigenarten + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +## Positionsfehler + +Das `PositionError`-Objekt wird an die `geolocationError`-Callback-Funktion übergeben, tritt ein Fehler mit navigator.geolocation. + +### Eigenschaften + +* **Code**: einer der vordefinierten Fehlercodes aufgeführt. + +* **Nachricht**: Fehlermeldung, die die Informationen über den aufgetretenen Fehler beschreibt. + +### Konstanten + +* `PositionError.PERMISSION_DENIED` + * Zurückgegeben, wenn Benutzer erlauben nicht die app Positionsinformationen abgerufen werden. Dies ist abhängig von der Plattform. +* `PositionError.POSITION_UNAVAILABLE` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position abzurufen ist. Im Allgemeinen bedeutet dies, dass das Gerät nicht mit einem Netzwerk verbunden ist oder ein Satelliten-Update kann nicht abgerufen werden. +* `PositionError.TIMEOUT` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position innerhalb der festgelegten Zeit abzurufen ist die `timeout` enthalten `geolocationOptions` . Bei Verwendung mit `navigator.geolocation.watchPosition` , könnte dieser Fehler wiederholt übergeben werden, zu der `geolocationError` Rückruf jedes `timeout` Millisekunden. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/es/README.md new file mode 100644 index 00000000..1a4bf006 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/es/README.md @@ -0,0 +1,266 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Este plugin proporciona información sobre la ubicación del dispositivo, tales como la latitud y longitud. Fuentes comunes de información de localización incluyen el sistema de posicionamiento Global (GPS) y ubicación deducido de las señales de la red como dirección IP, direcciones de RFID, WiFi y Bluetooth MAC y celulares GSM/CDMA IDs. No hay ninguna garantÃa de que la API devuelve la ubicación real del dispositivo. + +Esta API se basa en la [Especificación de API de geolocalización W3C](http://dev.w3.org/geo/api/spec-source.html) y sólo se ejecuta en dispositivos que ya no proporcionan una implementación. + +**ADVERTENCIA**: recopilación y uso de datos de geolocalización plantea cuestiones de privacidad importante. PolÃtica de privacidad de su aplicación debe discutir cómo la aplicación utiliza los datos de geolocalización, si se comparte con cualquiera de las partes y el nivel de precisión de los datos (por ejemplo, código postal grueso, fino, nivel, etc.). Datos de geolocalización es generalmente considerados sensibles porque puede revelar paradero del usuario y, si está almacenado, la historia de sus viajes. Por lo tanto, además de polÃtica de privacidad de la app, fuertemente considere dar un aviso de just-in-time antes de la aplicación tiene acceso a datos de geolocalización (si el sistema operativo del dispositivo ya no hacerlo). Que el aviso debe proporcionar la misma información mencionada, además de obtener un permiso del usuario (por ejemplo, presentando opciones para **Aceptar** y **No gracias**). Para obtener más información, por favor consulte a la guÃa de privacidad. + +Este plugin define un global `navigator.geolocation` objeto (para plataformas donde falta lo contrario). + +Aunque el objeto está en el ámbito global, caracterÃsticas proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Instalación + +Esto requiere cordova 5.0 + (1.0.0 estable actual) + + cordova plugin add cordova-plugin-geolocation + + +Las versiones más antiguas de Córdoba todavÃa pueden instalar mediante el id obsoleto (0.3.12 rancio) + + Cordova plugin agregar org.apache.cordova.geolocation + + +También es posible instalar directamente vÃa url repo (inestable) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + * Windows + +## Métodos + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Objetos (sólo lectura) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Devuelve la posición actual del dispositivo a la `geolocationSuccess` "callback" con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` "callback" pasa un `PositionError` objeto. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Parámetros + + * **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + + * **geolocationError**: *(opcional)* la devolución de llamada que se ejecuta si se produce un error. + + * **geolocationOptions**: *(opcional)* las opciones de geolocalización. + +### Ejemplo + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Devuelve la posición actual del dispositivo cuando se detecta un cambio de posición. Cuando el dispositivo recupera una nueva ubicación, el `geolocationSuccess` devolución de llamada se ejecuta con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` devolución de llamada se ejecuta con un `PositionError` objeto como parámetro. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parámetros + + * **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + + * **geolocationError**: (opcional) la devolución de llamada que se ejecuta si se produce un error. + + * **geolocationOptions**: opciones (opcional) la geolocalización. + +### Devoluciones + + * **Cadena**: devuelve un identificador de reloj que hace referencia el intervalo de posición del reloj. El id del reloj debe ser utilizado con `navigator.geolocation.clearWatch` para dejar de ver a los cambios de posición. + +### Ejemplo + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parámetros opcionales para personalizar la recuperación de la geolocalización`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opciones + + * **enableHighAccuracy**: proporciona una pista que la aplicación necesita los mejores resultados posibles. De forma predeterminada, el dispositivo intentará recuperar un `Position` usando métodos basados en red. Al establecer esta propiedad en `true` dice el marco a utilizar métodos más precisos, como el posicionamiento satelital. *(Boolean)* + + * **tiempo de espera**: la longitud máxima de tiempo (en milisegundos) que está permitido el paso de la llamada a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` hasta el correspondiente `geolocationSuccess` devolución de llamada se ejecuta. Si el `geolocationSuccess` no se invoque "callback" dentro de este tiempo, el `geolocationError` devolución de llamada se pasa un `PositionError.TIMEOUT` código de error. (Tenga en cuenta que cuando se utiliza en conjunción con `geolocation.watchPosition` , el `geolocationError` "callback" podrÃa ser llamado en un intervalo cada `timeout` milisegundos!) *(Número)* + + * **maximumAge**: aceptar un puesto en la memoria caché, cuya edad no es mayor que el tiempo especificado en milisegundos. *(Número)* + +### Rarezas Android + +Emuladores Android 2.x no devuelva un resultado de geolocalización a menos que el `enableHighAccuracy` opción se establece en`true`. + +## navigator.geolocation.clearWatch + +Deja de ver cambios en la ubicación del dispositivo al que hace referencia el `watchID` parámetro. + + navigator.geolocation.clearWatch(watchID); + + +### Parámetros + + * **watchID**: el id del intervalo `watchPosition` para despejar. (String) + +### Ejemplo + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene `Position` coordenadas y timestamp, creado por la API de geolocalización. + +### Propiedades + + * **coordenadas**: un conjunto de coordenadas geográficas. *(Coordenadas)* + + * **timestamp**: fecha y hora de creación `coords` . *(Fecha)* + +## Coordinates + +A `Coordinates` objeto está unido a un `Position` que está disponible para funciones de retrollamada en las solicitudes para la posición actual del objeto. Contiene un conjunto de propiedades que describen las coordenadas geográficas de posición. + +### Propiedades + + * **Latitude**: latitud en grados decimales. *(Número)* + + * **longitud**: longitud en grados decimales. *(Número)* + + * **altitud**: altura de la posición en metros por encima del elipsoide. *(Número)* + + * **exactitud**: nivel de precisión de las coordenadas de latitud y longitud en metros. *(Número)* + + * **altitudeAccuracy**: nivel de precisión de las coordenadas de altitud en metros. *(Número)* + + * **Dirección**: dirección del recorrido, especificado en grados contando hacia la derecha en relación con el norte verdadero. *(Número)* + + * **velocidad**: velocidad actual del dispositivo especificado en metros por segundo. *(Número)* + +### Amazon fuego OS rarezas + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +### Rarezas Android + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +## PositionError + +El `PositionError` objeto se pasa a la `geolocationError` función de devolución de llamada cuando se produce un error con navigator.geolocation. + +### Propiedades + + * **code**: uno de los códigos de error predefinido enumerados a continuación. + + * **mensaje**: mensaje de Error que describe los detalles del error encontrado. + +### Constantes + + * `PositionError.PERMISSION_DENIED` + * Regresó cuando los usuarios no permiten la aplicación recuperar información de la posición. Esto depende de la plataforma. + * `PositionError.POSITION_UNAVAILABLE` + * Regresó cuando el dispositivo es capaz de recuperar una posición. En general, esto significa que el dispositivo no está conectado a una red o no puede obtener una solución vÃa satélite. + * `PositionError.TIMEOUT` + * Cuando el dispositivo es capaz de recuperar una posición dentro del tiempo especificado por el `timeout` incluido en `geolocationOptions` . Cuando se utiliza con `navigator.geolocation.watchPosition` , este error podrÃa pasar repetidamente a la `geolocationError` "callback" cada `timeout` milisegundos.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/es/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/es/index.md new file mode 100644 index 00000000..043e9294 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/es/index.md @@ -0,0 +1,214 @@ +<!--- + 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-plugin-geolocation + +Este plugin proporciona información sobre la ubicación del dispositivo, tales como la latitud y longitud. Fuentes comunes de información de localización incluyen el sistema de posicionamiento Global (GPS) y ubicación deducido de las señales de la red como dirección IP, direcciones de RFID, WiFi y Bluetooth MAC y celulares GSM/CDMA IDs. No hay ninguna garantÃa de que la API devuelve la ubicación real del dispositivo. + +Esta API se basa en la [Especificación de API de geolocalización W3C][1] y sólo se ejecuta en dispositivos que ya no proporcionan una implementación. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**ADVERTENCIA**: recopilación y uso de datos de geolocalización plantea cuestiones de privacidad importante. PolÃtica de privacidad de su aplicación debe discutir cómo la aplicación utiliza los datos de geolocalización, si se comparte con cualquiera de las partes y el nivel de precisión de los datos (por ejemplo, código postal grueso, fino, nivel, etc.). Datos de geolocalización es generalmente considerados sensibles porque puede revelar paradero del usuario y, si está almacenado, la historia de sus viajes. Por lo tanto, además de polÃtica de privacidad de la app, fuertemente considere dar un aviso de just-in-time antes de la aplicación tiene acceso a datos de geolocalización (si el sistema operativo del dispositivo ya no hacerlo). Que el aviso debe proporcionar la misma información mencionada, además de obtener un permiso del usuario (por ejemplo, presentando opciones para **Aceptar** y **No gracias**). Para obtener más información, por favor consulte a la guÃa de privacidad. + +Este plugin define un global `navigator.geolocation` objeto (para plataformas donde falta lo contrario). + +Aunque el objeto está en el ámbito global, caracterÃsticas proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log ("navigator.geolocation funciona bien");} + + +## Instalación + + Cordova plugin agregar cordova-plugin-geolocation + + +## Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +## Métodos + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Objetos (sólo lectura) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Devuelve la posición actual del dispositivo a la `geolocationSuccess` "callback" con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` "callback" pasa un `PositionError` objeto. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Parámetros + +* **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + +* **geolocationError**: *(opcional)* la devolución de llamada que se ejecuta si se produce un error. + +* **geolocationOptions**: *(opcional)* las opciones de geolocalización. + +### Ejemplo + + onSuccess Callback / / este método acepta un objeto Position, que contiene el / / coordenadas GPS actual / / var onSuccess = function(position) {alert (' latitud: ' + position.coords.latitude + '\n' + ' longitud: ' + position.coords.longitude + '\n' + ' altitud: ' + position.coords.altitude + '\n' + ' exactitud: ' + position.coords.accuracy + '\n' + ' altitud exactitud: ' + position.coords.altitudeAccuracy + '\n' + ' hacia: ' + position.coords.heading + '\n' + ' velocidad: ' + position.coords.speed + '\n' + ' Timestamp: ' + position.timestamp + '\n');}; + + onError Callback recibe un objeto PositionError / / function onError(error) {alert (' código: ' + error.code + '\n' + ' mensaje: ' + error.message + '\n');} + + navigator.geolocation.getCurrentPosition (onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Devuelve la posición actual del dispositivo cuando se detecta un cambio de posición. Cuando el dispositivo recupera una nueva ubicación, el `geolocationSuccess` devolución de llamada se ejecuta con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` devolución de llamada se ejecuta con un `PositionError` objeto como parámetro. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Parámetros + +* **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + +* **geolocationError**: (opcional) la devolución de llamada que se ejecuta si se produce un error. + +* **geolocationOptions**: opciones (opcional) la geolocalización. + +### Devoluciones + +* **Cadena**: devuelve un identificador de reloj que hace referencia el intervalo de posición del reloj. El id del reloj debe ser utilizado con `navigator.geolocation.clearWatch` para dejar de ver a los cambios de posición. + +### Ejemplo + + onSuccess Callback / / este método acepta un objeto 'Position', que contiene / / coordenadas GPS de la corriente / / function onSuccess(position) {var elemento = document.getElementById('geolocation'); + element.innerHTML = ' latitud: ' + position.coords.latitude + ' < br / >' + ' longitud: ' + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML; + } / / onError Callback recibe un objeto PositionError / / function onError(error) {alert (' código: ' + error.code + '\n' + ' mensaje: ' + error.message + '\n');} + + Opciones: tira un error si no se recibe ninguna actualización cada 30 segundos. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parámetros opcionales para personalizar la recuperación de la geolocalización`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opciones + +* **enableHighAccuracy**: proporciona una pista que la aplicación necesita los mejores resultados posibles. De forma predeterminada, el dispositivo intentará recuperar un `Position` usando métodos basados en red. Al establecer esta propiedad en `true` dice el marco a utilizar métodos más precisos, como el posicionamiento satelital. *(Boolean)* + +* **tiempo de espera**: la longitud máxima de tiempo (en milisegundos) que está permitido el paso de la llamada a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` hasta el correspondiente `geolocationSuccess` devolución de llamada se ejecuta. Si el `geolocationSuccess` no se invoque "callback" dentro de este tiempo, el `geolocationError` devolución de llamada se pasa un `PositionError.TIMEOUT` código de error. (Tenga en cuenta que cuando se utiliza en conjunción con `geolocation.watchPosition` , el `geolocationError` "callback" podrÃa ser llamado en un intervalo cada `timeout` milisegundos!) *(Número)* + +* **maximumAge**: aceptar un puesto en la memoria caché, cuya edad no es mayor que el tiempo especificado en milisegundos. *(Número)* + +### Rarezas Android + +Emuladores Android 2.x no devuelva un resultado de geolocalización a menos que el `enableHighAccuracy` opción se establece en`true`. + +## navigator.geolocation.clearWatch + +Deja de ver cambios en la ubicación del dispositivo al que hace referencia el `watchID` parámetro. + + navigator.geolocation.clearWatch(watchID); + + +### Parámetros + +* **watchID**: el id del intervalo `watchPosition` para despejar. (String) + +### Ejemplo + + Opciones: ver los cambios en la posición y usar más / / exacta posición disponible del método de adquisición. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { enableHighAccuracy: true }); + + ... después de... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene `Position` coordenadas y timestamp, creado por la API de geolocalización. + +### Propiedades + +* **coordenadas**: un conjunto de coordenadas geográficas. *(Coordenadas)* + +* **timestamp**: fecha y hora de creación `coords` . *(Fecha)* + +## Coordinates + +A `Coordinates` objeto está unido a un `Position` que está disponible para funciones de retrollamada en las solicitudes para la posición actual del objeto. Contiene un conjunto de propiedades que describen las coordenadas geográficas de posición. + +### Propiedades + +* **Latitude**: latitud en grados decimales. *(Número)* + +* **longitud**: longitud en grados decimales. *(Número)* + +* **altitud**: altura de la posición en metros por encima del elipsoide. *(Número)* + +* **exactitud**: nivel de precisión de las coordenadas de latitud y longitud en metros. *(Número)* + +* **altitudeAccuracy**: nivel de precisión de las coordenadas de altitud en metros. *(Número)* + +* **Dirección**: dirección del recorrido, especificado en grados contando hacia la derecha en relación con el norte verdadero. *(Número)* + +* **velocidad**: velocidad actual del dispositivo especificado en metros por segundo. *(Número)* + +### Amazon fuego OS rarezas + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +### Rarezas Android + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +## PositionError + +El `PositionError` objeto se pasa a la `geolocationError` función de devolución de llamada cuando se produce un error con navigator.geolocation. + +### Propiedades + +* **code**: uno de los códigos de error predefinido enumerados a continuación. + +* **mensaje**: mensaje de Error que describe los detalles del error encontrado. + +### Constantes + +* `PositionError.PERMISSION_DENIED` + * Regresó cuando los usuarios no permiten la aplicación recuperar información de la posición. Esto depende de la plataforma. +* `PositionError.POSITION_UNAVAILABLE` + * Regresó cuando el dispositivo es capaz de recuperar una posición. En general, esto significa que el dispositivo no está conectado a una red o no puede obtener una solución vÃa satélite. +* `PositionError.TIMEOUT` + * Cuando el dispositivo es capaz de recuperar una posición dentro del tiempo especificado por el `timeout` incluido en `geolocationOptions` . Cuando se utiliza con `navigator.geolocation.watchPosition` , este error podrÃa pasar repetidamente a la `geolocationError` "callback" cada `timeout` milisegundos. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/fr/README.md new file mode 100644 index 00000000..f9865dc6 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/fr/README.md @@ -0,0 +1,227 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Ce plugin fournit des informations sur l'emplacement de l'appareil, tels que la latitude et la longitude. Les sources habituelles d'information incluent le Système de Positionnement Global (GPS) et la position déduite de signaux des réseaux tels que l'adresse IP, RFID, les adresses MAC WiFi et Bluetooth et les IDs cellulaires GSM/CDMA. Il n'y a cependant aucune garantie que cette API renvoie la position réelle de l'appareil. + +Cette API est basée sur la [Spécification de l'API Geolocation du W3C](http://dev.w3.org/geo/api/spec-source.html) et s'exécute uniquement sur les appareils qui n'en proposent pas déjà une implémentation. + +**Avertissement**: collecte et utilisation des données de géolocalisation soulève des questions importantes de la vie privée. La politique de confidentialité de votre application devrait traiter de la manière dont l'application utilise les données de géolocalisation, si elle les partage avec d'autres parties ou non et définir le niveau de précision de celles-ci (par exemple grossier, fin, restreint au code postal, etc.). Données de géolocalisation sont généralement considéré comme sensibles car elle peut révéler la localisation de l'utilisateur et, si stocké, l'histoire de leurs voyages. Par conséquent, en plus de la politique de confidentialité de l'application, vous devez envisager fortement fournissant un avis juste-à -temps, avant que l'application accède aux données de géolocalisation (si le système d'exploitation de périphérique n'est pas faire déjà ). Cette notice devrait contenir les informations susmentionnées, ainsi que permettre de recueillir l'autorisation de l'utilisateur (par exemple, en offrant les possibilités **OK** et **Non merci**). Pour plus d'informations, veuillez vous référer à la section "Guide du respect de la vie privée". + +Ce plugin définit un global `navigator.geolocation` objet (pour les plateformes où il est autrement manquant). + +Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log ("navigator.geolocation fonctionne bien");} + + +## Installation + +Pour cela, cordova 5.0 + (1.0.0 stable actuelle) + + cordova plugin add cordova-plugin-geolocation + + +Anciennes versions de cordova peuvent toujours installer via l'id obsolète (rassis 0.3.12) + + Cordova plugin ajouter org.apache.cordova.geolocation + + +Il est également possible d'installer directement via l'url de repo (instable) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + * Windows + +## Méthodes + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Objets (lecture seule) + + * Position + * PositionError + * Coordonnées + +## navigator.geolocation.getCurrentPosition + +Retourne la position actuelle de l'appareil à la `geolocationSuccess` rappel avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel est passé un `PositionError` objet. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + + * **geolocationSuccess** : la fonction callback à laquelle est transmise la position actuelle. + + * **geolocationError** : *(facultative)* la fonction callback s'exécutant si une erreur survient. + + * **geolocationOptions** : *(facultatives)* des préférences de géolocalisation. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet de Position, qui contient le / / coordonnées GPS actuel / / var onSuccess = function(position) {alert ('Latitude: ' + position.coords.latitude + « \n » + ' Longitude: ' + position.coords.longitude + « \n » + ' Altitude: ' + position.coords.altitude + « \n » + ' précision: ' + position.coords.accuracy + « \n » + ' Altitude précision: ' + position.coords.altitudeAccuracy + « \n » + ' rubrique: ' + position.coords.heading + « \n » + ' vitesse: ' + position.coords.speed + « \n » + ' Timestamp: ' + position.timestamp + « \n »);} ; + + onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: "+ error.code + « \n » + ' message: ' + error.message + « \n »);} + + navigator.geolocation.getCurrentPosition (onSuccess, onError) ; + + +## navigator.geolocation.watchPosition + +Retourne la position actuelle de l'appareil lorsqu'un changement de position est détecté. Lorsque l'appareil récupère un nouvel emplacement, le `geolocationSuccess` rappel s'exécute avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel s'exécute avec un `PositionError` objet comme paramètre. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + + * **geolocationSuccess** : la fonction callback à laquelle est transmise la position actuelle. + + * **geolocationError** : (facultative) la fonction callback s'exécutant lorsqu'une erreur survient. + + * **geolocationOptions** : (facultatives) options de personnalisation de la géolocalisation. + +### Retours + + * **Chaîne**: retourne un id de montre qui fait référence à l'intervalle de position montre. L'id de la montre doit être utilisé avec `navigator.geolocation.clearWatch` d'arrêter de regarder pour les changements de position. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet « Position », qui contient / / coordonnées de GPS le courant / / function onSuccess(position) {var element = document.getElementById('geolocation') ; + element.innerHTML = ' Latitude: "+ position.coords.latitude + ' < br / >' + ' Longitude:" + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML ; + } / / onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: ' + error.code + « \n » + "message: ' + error.message + « \n »);} + + Options : lever une erreur si aucune mise à jour n'est reçu toutes les 30 secondes. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { timeout: 30000 }) ; + + +## geolocationOptions + +Paramètres optionnels pour personnaliser la récupération de la géolocalisation`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true } ; + + +### Options + + * **enableHighAccuracy** : indique que l'application nécessite les meilleurs résultats possibles. Par défaut, l'appareil tente de récupérer une `Position` à l'aide de méthodes basées sur le réseau. Définir cette propriété à `true` demande à Cordova d'utiliser des méthodes plus précises, telles que la localisation par satellite. *(Boolean)* + + * **délai d'attente**: la longueur maximale de temps (en millisecondes) qui peut passer de l'appel à `navigator.geolocation.getCurrentPosition` ou `geolocation.watchPosition` jusqu'à ce que le correspondant `geolocationSuccess` rappel s'exécute. Si `geolocationSuccess` n'est pas appelée dans ce délai, le code d'erreur `PositionError.TIMEOUT` est transmis à la fonction callback `geolocationError`. (Notez que, dans le cas de `geolocation.watchPosition`, la fonction callback `geolocationError` pourrait être appelée à un intervalle régulier de `timeout` millisecondes !) *(Number)* + + * **maximumAge** : accepter une position mise en cache dont l'âge ne dépasse pas le délai spécifié en millisecondes. *(Number)* + +### Quirks Android + +Émulateurs Android 2.x ne pas retournent un résultat de géolocalisation, à moins que le `enableHighAccuracy` option est définie sur`true`. + +## navigator.geolocation.clearWatch + +Arrêter de regarder pour les modifications à l'emplacement de l'appareil référencé par le `watchID` paramètre. + + navigator.geolocation.clearWatch(watchID) ; + + +### Paramètres + + * **watchID** : l'identifiant de l'intervalle `watchPosition` à effacer. (String) + +### Exemple + + Options : suivi des modifications dans la position et utilise le plus / / exacte position méthode d'acquisition disponible. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { enableHighAccuracy: true }) ; + + .. plus sur... + + navigator.geolocation.clearWatch(watchID) ; + + +## Position + +Contient `Position` coordonnées et timestamp, créé par l'API de géolocalisation. + +### Propriétés + + * **coords** : un ensemble de coordonnées géographiques. *(Coordinates)* + + * **timestamp** : horodatage de la création de `coords`. *(Date)* + +## Coordonnées + +A `Coordinates` objet est attaché à un `Position` objet qui n'existe pas de fonctions de rappel dans les requêtes pour la position actuelle. Il contient un ensemble de propriétés qui décrivent les coordonnées géographiques d'une position. + +### Propriétés + + * **latitude** : latitude en degrés décimaux. *(Number)* + + * **longitude** : longitude en degrés décimaux. *(Number)* + + * **altitude** : hauteur de la position en mètres au-dessus de l'ellipsoïde. *(Number)* + + * **accuracy** : niveau de précision des valeurs de latitude et longitude, en mètres. *(Number)* + + * **altitudeAccuracy** : niveau de précision de la valeur d'altitude, en mètres. *(Number)* + + * **heading** : direction du trajet, indiquée en degrés comptés dans le sens horaire par rapport au vrai Nord. *(Number)* + + * **speed** : vitesse au sol actuelle de l'appareil, indiquée en mètres par seconde. *(Number)* + +### Amazon Fire OS Quirks + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +### Quirks Android + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +## PositionError + +Le `PositionError` objet est passé à la `geolocationError` fonction de rappel lorsqu'une erreur se produit avec navigator.geolocation. + +### Propriétés + + * **code**: l'un des codes d'erreur prédéfinis énumérés ci-dessous. + + * **message** : un message d'erreur détaillant l'erreur rencontrée. + +### Constantes + + * `PositionError.PERMISSION_DENIED` + * Retourné lorsque les utilisateurs ne permettent pas l'application extraire des informations de position. Cela dépend de la plate-forme. + * `PositionError.POSITION_UNAVAILABLE` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position. En général, cela signifie que l'appareil n'est pas connecté à un réseau ou ne peut pas obtenir un correctif de satellite. + * `PositionError.TIMEOUT` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position dans le délai précisé par le `timeout` inclus dans `geolocationOptions` . Lorsqu'il est utilisé avec `navigator.geolocation.watchPosition` , cette erreur pourrait être transmise à plusieurs reprises à la `geolocationError` rappel chaque `timeout` millisecondes.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/fr/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/fr/index.md new file mode 100644 index 00000000..bea18ddc --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/fr/index.md @@ -0,0 +1,214 @@ +<!--- + 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-plugin-geolocation + +Ce plugin fournit des informations sur l'emplacement de l'appareil, tels que la latitude et la longitude. Les sources habituelles d'information incluent le Système de Positionnement Global (GPS) et la position déduite de signaux des réseaux tels que l'adresse IP, RFID, les adresses MAC WiFi et Bluetooth et les IDs cellulaires GSM/CDMA. Il n'y a cependant aucune garantie que cette API renvoie la position réelle de l'appareil. + +Cette API est basée sur la [Spécification de l'API Geolocation du W3C][1] et s'exécute uniquement sur les appareils qui n'en proposent pas déjà une implémentation. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Avertissement**: collecte et utilisation des données de géolocalisation soulève des questions importantes de la vie privée. La politique de confidentialité de votre application devrait traiter de la manière dont l'application utilise les données de géolocalisation, si elle les partage avec d'autres parties ou non et définir le niveau de précision de celles-ci (par exemple grossier, fin, restreint au code postal, etc.). Données de géolocalisation sont généralement considéré comme sensibles car elle peut révéler la localisation de l'utilisateur et, si stocké, l'histoire de leurs voyages. Par conséquent, en plus de la politique de confidentialité de l'application, vous devez envisager fortement fournissant un avis juste-à -temps, avant que l'application accède aux données de géolocalisation (si le système d'exploitation de périphérique n'est pas faire déjà ). Cette notice devrait contenir les informations susmentionnées, ainsi que permettre de recueillir l'autorisation de l'utilisateur (par exemple, en offrant les possibilités **OK** et **Non merci**). Pour plus d'informations, veuillez vous référer à la section "Guide du respect de la vie privée". + +Ce plugin définit un global `navigator.geolocation` objet (pour les plateformes où il est autrement manquant). + +Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log ("navigator.geolocation fonctionne bien");} + + +## Installation + + Cordova plugin ajouter cordova-plugin-geolocation + + +## Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +## Méthodes + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Objets (lecture seule) + +* Position +* PositionError +* Coordonnées + +## navigator.geolocation.getCurrentPosition + +Retourne la position actuelle de l'appareil à la `geolocationSuccess` rappel avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel est passé un `PositionError` objet. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + +* **geolocationSuccess** : la fonction callback à laquelle est transmise la position actuelle. + +* **geolocationError** : *(facultative)* la fonction callback s'exécutant si une erreur survient. + +* **geolocationOptions** : *(facultatives)* des préférences de géolocalisation. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet de Position, qui contient le / / coordonnées GPS actuel / / var onSuccess = function(position) {alert ('Latitude: ' + position.coords.latitude + « \n » + ' Longitude: ' + position.coords.longitude + « \n » + ' Altitude: ' + position.coords.altitude + « \n » + ' précision: ' + position.coords.accuracy + « \n » + ' Altitude précision: ' + position.coords.altitudeAccuracy + « \n » + ' rubrique: ' + position.coords.heading + « \n » + ' vitesse: ' + position.coords.speed + « \n » + ' Timestamp: ' + position.timestamp + « \n »);} ; + + onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: "+ error.code + « \n » + ' message: ' + error.message + « \n »);} + + navigator.geolocation.getCurrentPosition (onSuccess, onError) ; + + +## navigator.geolocation.watchPosition + +Retourne la position actuelle de l'appareil lorsqu'un changement de position est détecté. Lorsque l'appareil récupère un nouvel emplacement, le `geolocationSuccess` rappel s'exécute avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel s'exécute avec un `PositionError` objet comme paramètre. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + +* **geolocationSuccess**: la fonction de rappel qui est passée de la position actuelle. + +* **geolocationError** : (facultative) la fonction callback s'exécutant lorsqu'une erreur survient. + +* **geolocationOptions** : (facultatives) options de personnalisation de la géolocalisation. + +### Retours + +* **Chaîne**: retourne un id de montre qui fait référence à l'intervalle de position montre. L'id de la montre doit être utilisé avec `navigator.geolocation.clearWatch` d'arrêter de regarder pour les changements de position. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet « Position », qui contient / / coordonnées de GPS le courant / / function onSuccess(position) {var element = document.getElementById('geolocation') ; + element.innerHTML = ' Latitude: "+ position.coords.latitude + ' < br / >' + ' Longitude:" + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML ; + } / / onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: ' + error.code + « \n » + "message: ' + error.message + « \n »);} + + Options : lever une erreur si aucune mise à jour n'est reçu toutes les 30 secondes. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { timeout: 30000 }) ; + + +## geolocationOptions + +Paramètres optionnels pour personnaliser la récupération de la géolocalisation`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true } ; + + +### Options + +* **enableHighAccuracy** : indique que l'application nécessite les meilleurs résultats possibles. Par défaut, l'appareil tente de récupérer une `Position` à l'aide de méthodes basées sur le réseau. Définir cette propriété à `true` demande à Cordova d'utiliser des méthodes plus précises, telles que la localisation par satellite. *(Boolean)* + +* **délai d'attente**: la longueur maximale de temps (en millisecondes) qui peut passer de l'appel à `navigator.geolocation.getCurrentPosition` ou `geolocation.watchPosition` jusqu'à ce que le correspondant `geolocationSuccess` rappel s'exécute. Si `geolocationSuccess` n'est pas appelée dans ce délai, le code d'erreur `PositionError.TIMEOUT` est transmis à la fonction callback `geolocationError`. (Notez que, dans le cas de `geolocation.watchPosition`, la fonction callback `geolocationError` pourrait être appelée à un intervalle régulier de `timeout` millisecondes !) *(Number)* + +* **maximumAge** : accepter une position mise en cache dont l'âge ne dépasse pas le délai spécifié en millisecondes. *(Number)* + +### Quirks Android + +Émulateurs Android 2.x ne pas retournent un résultat de géolocalisation, à moins que le `enableHighAccuracy` option est définie sur`true`. + +## navigator.geolocation.clearWatch + +Arrêter de regarder pour les modifications à l'emplacement de l'appareil référencé par le `watchID` paramètre. + + navigator.geolocation.clearWatch(watchID) ; + + +### Paramètres + +* **watchID** : l'identifiant de l'intervalle `watchPosition` à effacer. (String) + +### Exemple + + Options : suivi des modifications dans la position et utilise le plus / / exacte position méthode d'acquisition disponible. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { enableHighAccuracy: true }) ; + + .. plus sur... + + navigator.geolocation.clearWatch(watchID) ; + + +## Position + +Contient `Position` coordonnées et timestamp, créé par l'API de géolocalisation. + +### Propriétés + +* **coords** : un ensemble de coordonnées géographiques. *(Coordinates)* + +* **timestamp** : horodatage de la création de `coords`. *(Date)* + +## Coordonnées + +A `Coordinates` objet est attaché à un `Position` objet qui n'existe pas de fonctions de rappel dans les requêtes pour la position actuelle. Il contient un ensemble de propriétés qui décrivent les coordonnées géographiques d'une position. + +### Propriétés + +* **latitude** : latitude en degrés décimaux. *(Number)* + +* **longitude** : longitude en degrés décimaux. *(Number)* + +* **altitude** : hauteur de la position en mètres au-dessus de l'ellipsoïde. *(Number)* + +* **accuracy** : niveau de précision des valeurs de latitude et longitude, en mètres. *(Number)* + +* **altitudeAccuracy** : niveau de précision de la valeur d'altitude, en mètres. *(Number)* + +* **heading** : direction du trajet, indiquée en degrés comptés dans le sens horaire par rapport au vrai Nord. *(Number)* + +* **speed** : vitesse au sol actuelle de l'appareil, indiquée en mètres par seconde. *(Number)* + +### Amazon Fire OS Quirks + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +### Quirks Android + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +## PositionError + +Le `PositionError` objet est passé à la `geolocationError` fonction de rappel lorsqu'une erreur se produit avec navigator.geolocation. + +### Propriétés + +* **code**: l'un des codes d'erreur prédéfinis énumérés ci-dessous. + +* **message** : un message d'erreur détaillant l'erreur rencontrée. + +### Constantes + +* `PositionError.PERMISSION_DENIED` + * Retourné lorsque les utilisateurs ne permettent pas l'application extraire des informations de position. Cela dépend de la plate-forme. +* `PositionError.POSITION_UNAVAILABLE` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position. En général, cela signifie que l'appareil n'est pas connecté à un réseau ou ne peut pas obtenir un correctif de satellite. +* `PositionError.TIMEOUT` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position dans le délai précisé par le `timeout` inclus dans `geolocationOptions` . Lorsqu'il est utilisé avec `navigator.geolocation.watchPosition` , cette erreur pourrait être transmise à plusieurs reprises à la `geolocationError` rappel chaque `timeout` millisecondes. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/it/README.md new file mode 100644 index 00000000..8eb44be9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/it/README.md @@ -0,0 +1,268 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Questo plugin fornisce informazioni sulla posizione del dispositivo, come latitudine e longitudine. Comuni fonti di informazioni sulla posizione comprendono Global Positioning System (GPS) e posizione dedotta dai segnali di rete come indirizzo IP, indirizzi, RFID, WiFi e Bluetooth MAC e cellulare GSM/CDMA IDs. Non non c'è alcuna garanzia che l'API restituisce la posizione effettiva del dispositivo. + +Questa API è basata sulla [Specifica di W3C Geolocation API](http://dev.w3.org/geo/api/spec-source.html)e viene eseguito solo su dispositivi che non già forniscono un'implementazione. + +**Avviso**: raccolta e utilizzo dei dati di geolocalizzazione solleva questioni di privacy importante. Politica sulla privacy dell'app dovrebbe discutere come app utilizza dati di geolocalizzazione, se è condiviso con altre parti e il livello di precisione dei dati (ad esempio, Cap grossolana, fine, livello, ecc.). Dati di geolocalizzazione sono generalmente considerati sensibili perché può rivelare la sorte dell'utente e, se conservati, la storia dei loro viaggi. Pertanto, oltre alla politica di privacy dell'app, è fortemente consigliabile fornendo un preavviso di just-in-time prima app accede ai dati di geolocalizzazione (se il sistema operativo del dispositivo non farlo già ). Tale comunicazione deve fornire le informazioni stesse notate sopra, oltre ad ottenere l'autorizzazione (ad esempio, presentando scelte per **OK** e **No grazie**). Per ulteriori informazioni, vedere la guida sulla Privacy. + +Questo plugin definisce un oggetto globale `navigator.geolocation` (per le piattaforme dove altrimenti è manca). + +Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installazione + +Ciò richiede cordova 5.0 + (attuale stabile 1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +Versioni precedenti di cordova comunque possono installare tramite l'id deprecata (stantio 0.3.12) + + cordova plugin add org.apache.cordova.geolocation + + +È anche possibile installare direttamente tramite url di repo (instabile) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + * Windows + +## Metodi + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Oggetti (sola lettura) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Restituisce la posizione corrente del dispositivo il callback di `geolocationSuccess` con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene passato un oggetto `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + + * **geolocationSuccess**: il callback passato alla posizione corrente. + + * **geolocationError**: *(facoltativo)* il callback che viene eseguito se si verifica un errore. + + * **geolocationOptions**: *(opzionale)* le opzioni di geolocalizzazione. + +### Esempio + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Restituisce la posizione corrente del dispositivo quando viene rilevata una modifica della posizione. Quando il dispositivo recupera una nuova posizione, il callback `geolocationSuccess` esegue con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene eseguito con un oggetto `PositionError` come parametro. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + + * **geolocationSuccess**: il callback passato alla posizione corrente. + + * **geolocationError**: (facoltativo) il callback che viene eseguito se si verifica un errore. + + * **geolocationOptions**: opzioni (opzionale) la geolocalizzazione. + +### Restituisce + + * **Stringa**: restituisce un id di orologio che fa riferimento l'intervallo di posizione orologio. L'id dell'orologio deve essere usato con `navigator.geolocation.clearWatch` a smettere di guardare per cambiamenti di posizione. + +### Esempio + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametri opzionali per personalizzare il recupero di geolocalizzazione `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opzioni + + * **enableHighAccuracy**: fornisce un suggerimento che l'applicazione ha bisogno i migliori risultati possibili. Per impostazione predefinita, il dispositivo tenta di recuperare un `Position` usando metodi basati sulla rete. Impostando questa proprietà su `true` indica al framework di utilizzare metodi più accurati, come posizionamento satellitare. *(Boolean)* + + * **timeout**: la lunghezza massima di tempo (in millisecondi) che è consentito per passare dalla chiamata a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` fino a quando il corrispondente `geolocationSuccess` callback viene eseguito. Se il `geolocationSuccess` callback non viene richiamato entro questo tempo, il `geolocationError` callback viene passata una `PositionError.TIMEOUT` codice di errore. (Si noti che, quando utilizzato in combinazione con `geolocation.watchPosition` , il `geolocationError` callback potrebbe essere chiamato un intervallo ogni `timeout` millisecondi!) *(Numero)* + + * **maximumAge**: accettare una posizione memorizzata nella cache in cui età è minore il tempo specificato in millisecondi. *(Numero)* + +### Stranezze Android + +Emulatori Android 2. x non restituiscono un risultato di geolocalizzazione a meno che l'opzione `enableHighAccuracy` è impostata su `true`. + +## navigator.geolocation.clearWatch + +Smettere di guardare per le modifiche alla posizione del dispositivo a cui fa riferimento il parametro `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametri + + * **watchID**: l'id del `watchPosition` intervallo per cancellare. (String) + +### Esempio + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene le coordinate della `Position` e timestamp, creato da geolocation API. + +### Proprietà + + * **CoOrds**: un insieme di coordinate geografiche. *(Coordinate)* + + * **timestamp**: timestamp di creazione per `coords` . *(Data)* + +## Coordinates + +Un oggetto `Coordinates` è associato a un oggetto `Position` disponibile per le funzioni di callback in richieste per la posizione corrente. Contiene un insieme di proprietà che descrivono le coordinate geografiche di una posizione. + +### Proprietà + + * **latitudine**: latitudine in gradi decimali. *(Numero)* + + * **longitudine**: longitudine in gradi decimali. *(Numero)* + + * **altitudine**: altezza della posizione in metri sopra l'ellissoide. *(Numero)* + + * **accuratezza**: livello di accuratezza delle coordinate latitudine e longitudine in metri. *(Numero)* + + * **altitudeAccuracy**: livello di accuratezza della coordinata altitudine in metri. *(Numero)* + + * **rubrica**: senso di marcia, specificata in gradi in senso orario rispetto al vero nord di conteggio. *(Numero)* + + * **velocità **: velocità attuale terra del dispositivo, specificato in metri al secondo. *(Numero)* + +### Amazon fuoco OS stranezze + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +### Stranezze Android + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +## PositionError + +L'oggetto `PositionError` viene passato alla funzione di callback `geolocationError` quando si verifica un errore con navigator.geolocation. + +### Proprietà + + * **codice**: uno dei codici di errore predefiniti elencati di seguito. + + * **messaggio**: messaggio di errore che descrive i dettagli dell'errore rilevato. + +### Costanti + + * `PositionError.PERMISSION_DENIED` + * Restituito quando gli utenti non consentono l'applicazione recuperare le informazioni di posizione. Questo è dipendente dalla piattaforma. + * `PositionError.POSITION_UNAVAILABLE` + * Restituito quando il dispositivo è in grado di recuperare una posizione. In generale, questo significa che il dispositivo non è connesso a una rete o non può ottenere un fix satellitare. + * `PositionError.TIMEOUT` + * Restituito quando il dispositivo è in grado di recuperare una posizione entro il tempo specificato dal `timeout` incluso `geolocationOptions` . Quando utilizzato con `navigator.geolocation.watchPosition` , questo errore potrebbe essere passato più volte per la `geolocationError` richiamata ogni `timeout` millisecondi.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/it/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/it/index.md new file mode 100644 index 00000000..41412a07 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/it/index.md @@ -0,0 +1,255 @@ +<!--- + 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-plugin-geolocation + +Questo plugin fornisce informazioni sulla posizione del dispositivo, come latitudine e longitudine. Comuni fonti di informazioni sulla posizione comprendono Global Positioning System (GPS) e posizione dedotta dai segnali di rete come indirizzo IP, indirizzi, RFID, WiFi e Bluetooth MAC e cellulare GSM/CDMA IDs. Non non c'è alcuna garanzia che l'API restituisce la posizione effettiva del dispositivo. + +Questa API è basata sulla [Specifica di W3C Geolocation API][1]e viene eseguito solo su dispositivi che non già forniscono un'implementazione. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Avviso**: raccolta e utilizzo dei dati di geolocalizzazione solleva questioni di privacy importante. Politica sulla privacy dell'app dovrebbe discutere come app utilizza dati di geolocalizzazione, se è condiviso con altre parti e il livello di precisione dei dati (ad esempio, Cap grossolana, fine, livello, ecc.). Dati di geolocalizzazione sono generalmente considerati sensibili perché può rivelare la sorte dell'utente e, se conservati, la storia dei loro viaggi. Pertanto, oltre alla politica di privacy dell'app, è fortemente consigliabile fornendo un preavviso di just-in-time prima app accede ai dati di geolocalizzazione (se il sistema operativo del dispositivo non farlo già ). Tale comunicazione deve fornire le informazioni stesse notate sopra, oltre ad ottenere l'autorizzazione (ad esempio, presentando scelte per **OK** e **No grazie**). Per ulteriori informazioni, vedere la guida sulla Privacy. + +Questo plugin definisce un oggetto globale `navigator.geolocation` (per le piattaforme dove altrimenti è manca). + +Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installazione + + cordova plugin add cordova-plugin-geolocation + + +## Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +## Metodi + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Oggetti (sola lettura) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Restituisce la posizione corrente del dispositivo il callback di `geolocationSuccess` con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene passato un oggetto `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + +* **geolocationSuccess**: il callback passato alla posizione corrente. + +* **geolocationError**: *(facoltativo)* il callback che viene eseguito se si verifica un errore. + +* **geolocationOptions**: *(opzionale)* le opzioni di geolocalizzazione. + +### Esempio + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Restituisce la posizione corrente del dispositivo quando viene rilevata una modifica della posizione. Quando il dispositivo recupera una nuova posizione, il callback `geolocationSuccess` esegue con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene eseguito con un oggetto `PositionError` come parametro. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + +* **geolocationSuccess**: il callback passato alla posizione corrente. + +* **geolocationError**: (facoltativo) il callback che viene eseguito se si verifica un errore. + +* **geolocationOptions**: opzioni (opzionale) la geolocalizzazione. + +### Restituisce + +* **Stringa**: restituisce un id di orologio che fa riferimento l'intervallo di posizione orologio. L'id dell'orologio deve essere usato con `navigator.geolocation.clearWatch` a smettere di guardare per cambiamenti di posizione. + +### Esempio + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametri opzionali per personalizzare il recupero di geolocalizzazione `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opzioni + +* **enableHighAccuracy**: fornisce un suggerimento che l'applicazione ha bisogno i migliori risultati possibili. Per impostazione predefinita, il dispositivo tenta di recuperare un `Position` usando metodi basati sulla rete. Impostando questa proprietà su `true` indica al framework di utilizzare metodi più accurati, come posizionamento satellitare. *(Boolean)* + +* **timeout**: la lunghezza massima di tempo (in millisecondi) che è consentito per passare dalla chiamata a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` fino a quando il corrispondente `geolocationSuccess` callback viene eseguito. Se il `geolocationSuccess` callback non viene richiamato entro questo tempo, il `geolocationError` callback viene passata una `PositionError.TIMEOUT` codice di errore. (Si noti che, quando utilizzato in combinazione con `geolocation.watchPosition` , il `geolocationError` callback potrebbe essere chiamato un intervallo ogni `timeout` millisecondi!) *(Numero)* + +* **maximumAge**: accettare una posizione memorizzata nella cache in cui età è minore il tempo specificato in millisecondi. *(Numero)* + +### Stranezze Android + +Emulatori Android 2. x non restituiscono un risultato di geolocalizzazione a meno che l'opzione `enableHighAccuracy` è impostata su `true`. + +## navigator.geolocation.clearWatch + +Smettere di guardare per le modifiche alla posizione del dispositivo a cui fa riferimento il parametro `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametri + +* **watchID**: l'id del `watchPosition` intervallo per cancellare. (String) + +### Esempio + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene le coordinate della `Position` e timestamp, creato da geolocation API. + +### Proprietà + +* **CoOrds**: un insieme di coordinate geografiche. *(Coordinate)* + +* **timestamp**: timestamp di creazione per `coords` . *(Data)* + +## Coordinates + +Un oggetto `Coordinates` è associato a un oggetto `Position` disponibile per le funzioni di callback in richieste per la posizione corrente. Contiene un insieme di proprietà che descrivono le coordinate geografiche di una posizione. + +### Proprietà + +* **latitudine**: latitudine in gradi decimali. *(Numero)* + +* **longitudine**: longitudine in gradi decimali. *(Numero)* + +* **altitudine**: altezza della posizione in metri sopra l'ellissoide. *(Numero)* + +* **accuratezza**: livello di accuratezza delle coordinate latitudine e longitudine in metri. *(Numero)* + +* **altitudeAccuracy**: livello di accuratezza della coordinata altitudine in metri. *(Numero)* + +* **rubrica**: senso di marcia, specificata in gradi in senso orario rispetto al vero nord di conteggio. *(Numero)* + +* **velocità **: velocità attuale terra del dispositivo, specificato in metri al secondo. *(Numero)* + +### Amazon fuoco OS stranezze + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +### Stranezze Android + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +## PositionError + +L'oggetto `PositionError` viene passato alla funzione di callback `geolocationError` quando si verifica un errore con navigator.geolocation. + +### Proprietà + +* **codice**: uno dei codici di errore predefiniti elencati di seguito. + +* **messaggio**: messaggio di errore che descrive i dettagli dell'errore rilevato. + +### Costanti + +* `PositionError.PERMISSION_DENIED` + * Restituito quando gli utenti non consentono l'applicazione recuperare le informazioni di posizione. Questo è dipendente dalla piattaforma. +* `PositionError.POSITION_UNAVAILABLE` + * Restituito quando il dispositivo è in grado di recuperare una posizione. In generale, questo significa che il dispositivo non è connesso a una rete o non può ottenere un fix satellitare. +* `PositionError.TIMEOUT` + * Restituito quando il dispositivo è in grado di recuperare una posizione entro il tempo specificato dal `timeout` incluso `geolocationOptions` . Quando utilizzato con `navigator.geolocation.watchPosition` , questo errore potrebbe essere passato più volte per la `geolocationError` richiamata ogni `timeout` millisecondi. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ja/README.md new file mode 100644 index 00000000..a519d2c2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ja/README.md @@ -0,0 +1,268 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +ã“ã®ãƒ—ラグインã¯ç·¯åº¦ã‚„経度ãªã©ã®ãƒ‡ãƒã‚¤ã‚¹ã®å ´æ‰€ã«é–¢ã™ã‚‹æƒ…å ±ã‚’æä¾›ã—ã¾ã™ã€‚ ä½ç½®æƒ…å ±ã®å…±é€šã®ã‚½ãƒ¼ã‚¹ã¯ã‚°ãƒãƒ¼ãƒãƒ« ãƒã‚¸ã‚·ãƒ§ãƒ‹ãƒ³ã‚° システム(GPS) 㨠IP アドレスã€RFIDã€WiFi ãŠã‚ˆã³ Bluetooth ã® MAC アドレスã€ãŠã‚ˆã³ GSM/cdma æ–¹å¼æºå¸¯ Id ãªã©ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ä¿¡å·ã‹ã‚‰æŽ¨å®šã•ã‚Œã‚‹å ´æ‰€ã«ã‚‚ã‚りã¾ã™ã€‚ API ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®å®Ÿéš›ã®å ´æ‰€ã‚’è¿”ã™ã“ã¨ã®ä¿è¨¼ã¯ã‚りã¾ã›ã‚“。 + +ã“ã® API ã¯[W3C 地ç†ä½ç½®æƒ…å ± API 仕様](http://dev.w3.org/geo/api/spec-source.html)ã«åŸºã¥ã„ã¦ãŠã‚Šã€æ—¢ã«å®Ÿè£…ã‚’æä¾›ã—ãªã„デãƒã‚¤ã‚¹ä¸Šã®ã¿ã§å®Ÿè¡Œã—ã¾ã™ã€‚ + +**è¦å‘Š**: 地ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã®åŽé›†ã¨åˆ©ç”¨ã‚’é‡è¦ãªãƒ—ライãƒã‚·ãƒ¼ã®å•題を発生ã•ã›ã¾ã™ã€‚ アプリã®ãƒ—ライãƒã‚·ãƒ¼ ãƒãƒªã‚·ãƒ¼ã¯ä»–ã®å½“事者ã¨ãƒ‡ãƒ¼ã‚¿ (ãŸã¨ãˆã°ã€ç²—ã„ã€ç½°é‡‘ã€éƒµä¾¿ç•ªå·ãƒ¬ãƒ™ãƒ«ã€ç‰) ã®ç²¾åº¦ã®ãƒ¬ãƒ™ãƒ«ã§ã¯å…±æœ‰ã•れã¦ã„ã‚‹ã‹ã©ã†ã‹ã€ã‚¢ãƒ—リãŒåœ°ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã‚’ä½¿ç”¨ã™ã‚‹æ–¹æ³•ã‚’è°è«–ã™ã¹ãã§ã™ã€‚ 地ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã¨ä¸€èˆ¬ã«è¦‹ãªã•ã‚Œã‚‹æ•æ„Ÿãªãƒ¦ãƒ¼ã‚¶ãƒ¼ã®å±…å ´æ‰€ã‚’é–‹ç¤ºã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã®ã§ã€å½¼ã‚‰ã®æ—…è¡Œã®æ´å²ä¿å˜ã•れã¦ã„ã‚‹å ´åˆã€‚ ã—ãŸãŒã£ã¦ã€ã‚¢ãƒ—リã®ãƒ—ライãƒã‚·ãƒ¼ ãƒãƒªã‚·ãƒ¼ã«åŠ ãˆã¦ã€å¼·ãã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ (デãƒã‚¤ã‚¹ オペレーティング システムã—ãªã„å ´åˆãã†æ—¢ã«)ã€ã‚¢ãƒ—リケーションã«åœ°ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã‚’ã‚¢ã‚¯ã‚»ã‚¹ã™ã‚‹å‰ã« - 時間ã®ãŠçŸ¥ã‚‰ã›ã‚’æä¾›ã—ã¾ã™ã€‚ ãã®é€šçŸ¥ã¯ã€ä¸Šè¨˜ã® (例ãˆã°ã€ **[ok]**ã‚’**ãŠã‹ã’ã§**é¸æŠžè‚¢ã‚’æç¤ºã™ã‚‹) ã«ã‚ˆã£ã¦ãƒ¦ãƒ¼ã‚¶ãƒ¼ã®ã‚¢ã‚¯ã‚»ã‚¹è¨±å¯ã‚’å–å¾—ã™ã‚‹ã ã‘ã§ãªãã€åŒã˜æƒ…å ±ã‚’æä¾›ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚ 詳細ã«ã¤ã„ã¦ã¯ã€ãƒ—ライãƒã‚·ãƒ¼ã«é–¢ã™ã‚‹ã‚¬ã‚¤ãƒ‰ã‚’å‚ç…§ã—ã¦ãã ã•ã„。 + +ã“ã®ãƒ—ラグインã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« `navigator.geolocation` オブジェクト (ãƒ—ãƒ©ãƒƒãƒˆãƒ•ã‚©ãƒ¼ãƒ è¡Œæ–¹ä¸æ˜Žã§ã™ãれ以外ã®å ´åˆ) を定義ã—ã¾ã™ã€‚ + +オブジェクトã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã§ã™ãŒã€ã“ã®ãƒ—ラグインã«ã‚ˆã£ã¦æä¾›ã•れる機能ã¯ã€`deviceready` イベントã®å¾Œã¾ã§ä½¿ç”¨ã§ãã¾ã›ã‚“。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## インストール + +ã“れã¯ã‚³ãƒ«ãƒ‰ãƒ 5.0 + (ç¾åœ¨å®‰å®š 1.0.0) ã‚’å¿…è¦ã¨ã—ã¾ã™ã€‚ + + cordova plugin add cordova-plugin-geolocation + + +コルドãƒã®å¤ã„ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã§ã‚‚éžæŽ¨å¥¨ id (å¤ã„ 0.3.12 ã¨) 経由ã§ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã§ãã¾ã™ã€‚ + + cordova plugin add org.apache.cordova.geolocation + + +ã¾ãŸã€ãƒ¬ãƒã® url 経由ã§ç›´æŽ¥ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã™ã‚‹ã“ã¨ãŒå¯èƒ½ã (ä¸å®‰å®š) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * Firefox ã® OS + * iOS + * Tizen + * Windows Phone 7 㨠8 + * Windows 8 + * Windows + +## メソッド + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## オブジェクト (èªã¿å–り専用) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +`Position` オブジェクトを `geolocationSuccess` コールãƒãƒƒã‚¯ã«ãƒ‘ラメーターã¨ã—ã¦ãƒ‡ãƒã‚¤ã‚¹ã®ç¾åœ¨ä½ç½®ã‚’è¿”ã—ã¾ã™ã€‚ エラーãŒã‚ã‚‹å ´åˆ `geolocationError` コールãƒãƒƒã‚¯ã«ã¯ã€`PositionError` ã‚ªãƒ–ã‚¸ã‚§ã‚¯ãƒˆãŒæ¸¡ã•れã¾ã™ã€‚ + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + + * **geolocationSuccess**: ç¾åœ¨ã®ä½ç½®ã‚’渡ã•れるコールãƒãƒƒã‚¯ã€‚ + + * **geolocationError**: *(çœç•¥å¯èƒ½)*エラーãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•れるコールãƒãƒƒã‚¯ã€‚ + + * **geolocationOptions**: *(オプション)*地ç†ä½ç½®æƒ…å ±ã®ã‚ªãƒ—ションã§ã™ã€‚ + +### 例 + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +ä½ç½®ã®å¤‰æ›´ãŒæ¤œå‡ºã•れãŸå ´åˆã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®ç¾åœ¨ä½ç½®ã‚’è¿”ã—ã¾ã™ã€‚ å–å¾—ã•れるã¨ã€ãƒ‡ãƒã‚¤ã‚¹ã®æ–°ã—ã„å ´æ‰€ã€`geolocationSuccess` コールãƒãƒƒã‚¯ パラメーターã¨ã—㦠`ä½ç½®` オブジェクトを実行ã—ã¾ã™ã€‚ エラーãŒã‚ã‚‹å ´åˆã€`geolocationError` コールãƒãƒƒã‚¯ パラメーターã¨ã—㦠`PositionError` オブジェクトã§å®Ÿè¡Œã—ã¾ã™ã€‚ + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + + * **geolocationSuccess**: ç¾åœ¨ã®ä½ç½®ã‚’渡ã•れるコールãƒãƒƒã‚¯ã€‚ + + * **geolocationError**: (çœç•¥å¯èƒ½) エラーãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•れるコールãƒãƒƒã‚¯ã€‚ + + * **geolocationOptions**: (オプション) 地ç†ä½ç½®æƒ…å ±ã®ã‚ªãƒ—ションã§ã™ã€‚ + +### è¿”ã—ã¾ã™ + + * **æ–‡å—列**: 時計ã®ä½ç½®ã®é–“隔をå‚ç…§ã™ã‚‹æ™‚計 id ã‚’è¿”ã—ã¾ã™ã€‚ 時計 id ã§ä½¿ç”¨ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ `navigator.geolocation.clearWatch` åœæ¢ä½ç½®ã®å¤‰åŒ–を監視ã—ã¾ã™ã€‚ + +### 例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +地ç†ä½ç½®æƒ…å ± `ã®ä½ç½®` ã®æ¤œç´¢ã‚’カスタマイズã™ã‚‹ãŸã‚ã®çœç•¥å¯èƒ½ãªãƒ‘ラメーター. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### オプション + + * **enableHighAccuracy**: 最高ã®çµæžœãŒã€ã‚¢ãƒ—リケーションã«å¿…è¦ãŒã‚ã‚‹ã“ã¨ã®ãƒ’ントを示ã—ã¾ã™ã€‚ 既定ã§ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®å–得を試ã¿ã¾ã™ã€ `Position` ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ ベースã®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’使用ã—ã¾ã™ã€‚ ã“ã®ãƒ—ãƒãƒ‘ティをè¨å®šã™ã‚‹ `true` 衛星測ä½ãªã©ã®ã‚ˆã‚Šæ£ç¢ºãªæ–¹æ³•を使用ã™ã‚‹ãŸã‚ã«ãƒ•ãƒ¬ãƒ¼ãƒ ãƒ¯ãƒ¼ã‚¯ã«æŒ‡ç¤ºã—ã¾ã™ã€‚ *(ブール値)* + + * **タイムアウト**: ã¸ã®å‘¼ã³å‡ºã—ã‹ã‚‰é€šéŽãŒè¨±å¯ã•れる時間 (ミリ秒å˜ä½) ã®æœ€å¤§é•· `navigator.geolocation.getCurrentPosition` ã¾ãŸã¯ `geolocation.watchPosition` ã¾ã§å¯¾å¿œã™ã‚‹ã€ `geolocationSuccess` コールãƒãƒƒã‚¯ã‚’実行ã—ã¾ã™ã€‚ å ´åˆã¯ã€ `geolocationSuccess` ã“ã®æ™‚間内ã«ã€ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã¯å‘¼ã³å‡ºã•れã¾ã›ã‚“〠`geolocationError` コールãƒãƒƒã‚¯ã«æ¸¡ã•れる〠`PositionError.TIMEOUT` ã®ã‚¨ãƒ©ãƒ¼ コード。 (ã¨çµ„ã¿åˆã‚ã›ã¦ä½¿ç”¨ã™ã‚‹ã¨ãã«æ³¨æ„ã—ã¦ãã ã•ã„ `geolocation.watchPosition` ã® `geolocationError` é–“éš”ã§ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã‚’呼ã³å‡ºã™ã“ã¨ãŒã§ãã¾ã™ã™ã¹ã¦ `timeout` ミリ秒 ï¼)*(æ•°)* + + * **maximumAge**: å¹´é½¢ãŒã‚るミリ秒å˜ä½ã§æŒ‡å®šã—ãŸæ™‚間よりも大ãããªã„ã‚ャッシュã•れãŸä½ç½®ã‚’å—ã‘入れã¾ã™ã€‚*(æ•°)* + +### Android ã®ç™– + +`enableHighAccuracy` オプション㌠`true` ã«è¨å®šã—ãªã„é™ã‚Šã€ã‚¢ãƒ³ãƒ‰ãƒã‚¤ãƒ‰ 2.x エミュレーター地ç†ä½ç½®æƒ…å ±ã®çµæžœã‚’è¿”ã•ãªã„. + +## navigator.geolocation.clearWatch + +`watchID` パラメーターã«ã‚ˆã£ã¦å‚ç…§ã•れるã€ãƒ‡ãƒã‚¤ã‚¹ã®å ´æ‰€ã¸ã®å¤‰æ›´ã‚’見ã¦åœæ¢ã—ã¾ã™ã€‚ + + navigator.geolocation.clearWatch(watchID); + + +### パラメーター + + * **watchID**: ã® id〠`watchPosition` をクリアã™ã‚‹é–“隔。(æ–‡å—列) + +### 例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 座標ã¨åœ°ç†ä½ç½®æƒ…å ± API ã§ä½œæˆã•れãŸã‚¿ã‚¤ãƒ スタンプãŒå«ã¾ã‚Œã¾ã™ã€‚ + +### プãƒãƒ‘ティ + + * **coords**: 地ç†çš„座標ã®ã‚»ãƒƒãƒˆã€‚*(座標)* + + * **timestamp**: 作æˆã®ã‚¿ã‚¤ãƒ スタンプを `coords` 。*(日)* + +## Coordinates + +`Coordinates` ã®ã‚ªãƒ–ジェクトã¯ç¾åœ¨ã®ä½ç½®ã®ãŸã‚ã®è¦æ±‚ã§ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯é–¢æ•°ã«ä½¿ç”¨ã™ã‚‹ `Position` オブジェクトã«ã‚¢ã‚¿ãƒƒãƒã•れã¾ã™ã€‚ ä½ç½®ã®åœ°ç†åº§æ¨™ã‚’記述ã™ã‚‹ãƒ—ãƒãƒ‘ティã®ã‚»ãƒƒãƒˆãŒå«ã¾ã‚Œã¦ã„ã¾ã™ã€‚ + +### プãƒãƒ‘ティ + + * **latitude**: 10 度緯度。*(æ•°)* + + * **longitude**: 10 進度ã®çµŒåº¦ã€‚*(æ•°)* + + * **altitude**: 楕円体上ã®ãƒ¡ãƒ¼ãƒˆãƒ«ã®ä½ç½®ã®é«˜ã•。*(æ•°)* + + * **accuracy**: メートルã®ç·¯åº¦ã¨çµŒåº¦åº§æ¨™ã®ç²¾åº¦ãƒ¬ãƒ™ãƒ«ã€‚*(æ•°)* + + * **altitudeAccuracy**: メートルã®é«˜åº¦åº§æ¨™ã®ç²¾åº¦ãƒ¬ãƒ™ãƒ«ã€‚*(æ•°)* + + * **headingã—**: 進行方å‘ã€ã‚«ã‚¦ãƒ³ãƒˆã€çœŸåŒ—ã‹ã‚‰æ™‚計回りã®è§’åº¦ã§æŒ‡å®šã—ã¾ã™ã€‚*(æ•°)* + + * **speed**: æ¯Žç§’ãƒ¡ãƒ¼ãƒˆãƒ«ã§æŒ‡å®šã•れãŸãƒ‡ãƒã‚¤ã‚¹ã®ç¾åœ¨ã®å¯¾åœ°é€Ÿåº¦ã€‚*(æ•°)* + +### ã‚¢ãƒžã‚¾ãƒ³ç« OS ç™– + +**altitudeAccuracy**: `null` ã‚’è¿”ã™ã“ã¨ã® Android デãƒã‚¤ã‚¹ã§ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“. + +### Android ã®ç™– + +**altitudeAccuracy**: `null` ã‚’è¿”ã™ã“ã¨ã® Android デãƒã‚¤ã‚¹ã§ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“. + +## PositionError + +`PositionError` オブジェクト navigator.geolocation ã§ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ãŸã¨ãã« `geolocationError` コールãƒãƒƒã‚¯é–¢æ•°ã«æ¸¡ã•れã¾ã™ã€‚ + +### プãƒãƒ‘ティ + + * **コード**: 次ã®ã„ãšã‚Œã‹ã®å®šç¾©æ¸ˆã¿ã®ã‚¨ãƒ©ãƒ¼ コード。 + + * **message**: 発生ã—ãŸã‚¨ãƒ©ãƒ¼ã®è©³ç´°ã‚’説明ã™ã‚‹ã‚¨ãƒ©ãƒ¼ メッセージ。 + +### 定数 + + * `PositionError.PERMISSION_DENIED` + * ユーザーã®ä½ç½®æƒ…å ±ã‚’å–å¾—ã™ã‚‹ã‚¢ãƒ—リを許å¯ã—ãªã„å ´åˆã«è¿”ã•れã¾ã™ã€‚ã“れã¯ãƒ—ラットフォームã«ä¾å˜ã—ã¾ã™ã€‚ + * `PositionError.POSITION_UNAVAILABLE` + * デãƒã‚¤ã‚¹ãŒã€ä½ç½®ã‚’å–å¾—ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™è¿”ã•れã¾ã™ã€‚一般ã«ã€ã¤ã¾ã‚Šã€ãƒ‡ãƒã‚¤ã‚¹ãŒãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ã«æŽ¥ç¶šã•れã¦ã„ãªã„ã¾ãŸã¯è¡›æ˜Ÿã®ä¿®æ£ã‚’å¾—ã‚‹ã“ã¨ãŒã§ãã¾ã›ã‚“。 + * `PositionError.TIMEOUT` + * デãƒã‚¤ã‚¹ãŒã§æŒ‡å®šã•ã‚ŒãŸæ™‚間内ã®ä½ç½®ã‚’å–å¾—ã™ã‚‹ã“ã¨ãŒã§ãã‚‹ã¨ãã«è¿”ã•れる〠`timeout` ã«å«ã¾ã‚Œã¦ã„ã‚‹ `geolocationOptions` 。 使用ã™ã‚‹ã¨ `navigator.geolocation.watchPosition` ã€ã“ã®ã‚¨ãƒ©ãƒ¼ãŒç¹°ã‚Šè¿”ã—ã«æ¸¡ã™ã“ã¨ãŒã€ `geolocationError` コールãƒãƒƒã‚¯ã”㨠`timeout` (ミリ秒å˜ä½)。
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/ja/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ja/index.md new file mode 100644 index 00000000..3a8b73a5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ja/index.md @@ -0,0 +1,255 @@ +<!--- + 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-plugin-geolocation + +ã“ã®ãƒ—ラグインã¯ç·¯åº¦ã‚„経度ãªã©ã®ãƒ‡ãƒã‚¤ã‚¹ã®å ´æ‰€ã«é–¢ã™ã‚‹æƒ…å ±ã‚’æä¾›ã—ã¾ã™ã€‚ ä½ç½®æƒ…å ±ã®å…±é€šã®ã‚½ãƒ¼ã‚¹ã¯ã‚°ãƒãƒ¼ãƒãƒ« ãƒã‚¸ã‚·ãƒ§ãƒ‹ãƒ³ã‚° システム(GPS) 㨠IP アドレスã€RFIDã€WiFi ãŠã‚ˆã³ Bluetooth ã® MAC アドレスã€ãŠã‚ˆã³ GSM/cdma æ–¹å¼æºå¸¯ Id ãªã©ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ä¿¡å·ã‹ã‚‰æŽ¨å®šã•ã‚Œã‚‹å ´æ‰€ã«ã‚‚ã‚りã¾ã™ã€‚ API ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®å®Ÿéš›ã®å ´æ‰€ã‚’è¿”ã™ã“ã¨ã®ä¿è¨¼ã¯ã‚りã¾ã›ã‚“。 + +ã“ã® API ã¯[W3C 地ç†ä½ç½®æƒ…å ± API 仕様][1]ã«åŸºã¥ã„ã¦ãŠã‚Šã€æ—¢ã«å®Ÿè£…ã‚’æä¾›ã—ãªã„デãƒã‚¤ã‚¹ä¸Šã®ã¿ã§å®Ÿè¡Œã—ã¾ã™ã€‚ + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**è¦å‘Š**: 地ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã®åŽé›†ã¨åˆ©ç”¨ã‚’é‡è¦ãªãƒ—ライãƒã‚·ãƒ¼ã®å•題を発生ã•ã›ã¾ã™ã€‚ アプリã®ãƒ—ライãƒã‚·ãƒ¼ ãƒãƒªã‚·ãƒ¼ã¯ä»–ã®å½“事者ã¨ãƒ‡ãƒ¼ã‚¿ (ãŸã¨ãˆã°ã€ç²—ã„ã€ç½°é‡‘ã€éƒµä¾¿ç•ªå·ãƒ¬ãƒ™ãƒ«ã€ç‰) ã®ç²¾åº¦ã®ãƒ¬ãƒ™ãƒ«ã§ã¯å…±æœ‰ã•れã¦ã„ã‚‹ã‹ã©ã†ã‹ã€ã‚¢ãƒ—リãŒåœ°ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã‚’ä½¿ç”¨ã™ã‚‹æ–¹æ³•ã‚’è°è«–ã™ã¹ãã§ã™ã€‚ 地ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã¨ä¸€èˆ¬ã«è¦‹ãªã•ã‚Œã‚‹æ•æ„Ÿãªãƒ¦ãƒ¼ã‚¶ãƒ¼ã®å±…å ´æ‰€ã‚’é–‹ç¤ºã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã®ã§ã€å½¼ã‚‰ã®æ—…è¡Œã®æ´å²ä¿å˜ã•れã¦ã„ã‚‹å ´åˆã€‚ ã—ãŸãŒã£ã¦ã€ã‚¢ãƒ—リã®ãƒ—ライãƒã‚·ãƒ¼ ãƒãƒªã‚·ãƒ¼ã«åŠ ãˆã¦ã€å¼·ãã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ (デãƒã‚¤ã‚¹ オペレーティング システムã—ãªã„å ´åˆãã†æ—¢ã«)ã€ã‚¢ãƒ—リケーションã«åœ°ç†ä½ç½®æƒ…å ±ãƒ‡ãƒ¼ã‚¿ã‚’ã‚¢ã‚¯ã‚»ã‚¹ã™ã‚‹å‰ã« - 時間ã®ãŠçŸ¥ã‚‰ã›ã‚’æä¾›ã—ã¾ã™ã€‚ ãã®é€šçŸ¥ã¯ã€ä¸Šè¨˜ã® (例ãˆã°ã€ **[ok]**ã‚’**ãŠã‹ã’ã§**é¸æŠžè‚¢ã‚’æç¤ºã™ã‚‹) ã«ã‚ˆã£ã¦ãƒ¦ãƒ¼ã‚¶ãƒ¼ã®ã‚¢ã‚¯ã‚»ã‚¹è¨±å¯ã‚’å–å¾—ã™ã‚‹ã ã‘ã§ãªãã€åŒã˜æƒ…å ±ã‚’æä¾›ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚ 詳細ã«ã¤ã„ã¦ã¯ã€ãƒ—ライãƒã‚·ãƒ¼ã«é–¢ã™ã‚‹ã‚¬ã‚¤ãƒ‰ã‚’å‚ç…§ã—ã¦ãã ã•ã„。 + +ã“ã®ãƒ—ラグインã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« `navigator.geolocation` オブジェクト (ãƒ—ãƒ©ãƒƒãƒˆãƒ•ã‚©ãƒ¼ãƒ è¡Œæ–¹ä¸æ˜Žã§ã™ãれ以外ã®å ´åˆ) を定義ã—ã¾ã™ã€‚ + +オブジェクトã¯ã€ã‚°ãƒãƒ¼ãƒãƒ« スコープã§ã§ã™ãŒã€ã“ã®ãƒ—ラグインã«ã‚ˆã£ã¦æä¾›ã•れる機能ã¯ã€`deviceready` イベントã®å¾Œã¾ã§ä½¿ç”¨ã§ãã¾ã›ã‚“。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## インストール + + cordova plugin add cordova-plugin-geolocation + + +## サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* Firefox ã® OS +* iOS +* Tizen +* Windows Phone 7 㨠8 +* Windows 8 + +## メソッド + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## オブジェクト (èªã¿å–り専用) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +`Position` オブジェクトを `geolocationSuccess` コールãƒãƒƒã‚¯ã«ãƒ‘ラメーターã¨ã—ã¦ãƒ‡ãƒã‚¤ã‚¹ã®ç¾åœ¨ä½ç½®ã‚’è¿”ã—ã¾ã™ã€‚ エラーãŒã‚ã‚‹å ´åˆ `geolocationError` コールãƒãƒƒã‚¯ã«ã¯ã€`PositionError` ã‚ªãƒ–ã‚¸ã‚§ã‚¯ãƒˆãŒæ¸¡ã•れã¾ã™ã€‚ + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + +* **geolocationSuccess**: ç¾åœ¨ã®ä½ç½®ã‚’渡ã•れるコールãƒãƒƒã‚¯ã€‚ + +* **geolocationError**: *(çœç•¥å¯èƒ½)*エラーãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•れるコールãƒãƒƒã‚¯ã€‚ + +* **geolocationOptions**: *(オプション)*地ç†ä½ç½®æƒ…å ±ã®ã‚ªãƒ—ションã§ã™ã€‚ + +### 例 + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +ä½ç½®ã®å¤‰æ›´ãŒæ¤œå‡ºã•れãŸå ´åˆã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®ç¾åœ¨ä½ç½®ã‚’è¿”ã—ã¾ã™ã€‚ å–å¾—ã•れるã¨ã€ãƒ‡ãƒã‚¤ã‚¹ã®æ–°ã—ã„å ´æ‰€ã€`geolocationSuccess` コールãƒãƒƒã‚¯ パラメーターã¨ã—㦠`ä½ç½®` オブジェクトを実行ã—ã¾ã™ã€‚ エラーãŒã‚ã‚‹å ´åˆã€`geolocationError` コールãƒãƒƒã‚¯ パラメーターã¨ã—㦠`PositionError` オブジェクトã§å®Ÿè¡Œã—ã¾ã™ã€‚ + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + +* **geolocationSuccess**: ç¾åœ¨ã®ä½ç½®ã‚’渡ã•れるコールãƒãƒƒã‚¯ã€‚ + +* **geolocationError**: (çœç•¥å¯èƒ½) エラーãŒç™ºç”Ÿã—ãŸå ´åˆã«å®Ÿè¡Œã•れるコールãƒãƒƒã‚¯ã€‚ + +* **geolocationOptions**: (オプション) 地ç†ä½ç½®æƒ…å ±ã®ã‚ªãƒ—ションã§ã™ã€‚ + +### è¿”ã—ã¾ã™ + +* **æ–‡å—列**: 時計ã®ä½ç½®ã®é–“隔をå‚ç…§ã™ã‚‹æ™‚計 id ã‚’è¿”ã—ã¾ã™ã€‚ 時計 id ã§ä½¿ç”¨ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ `navigator.geolocation.clearWatch` åœæ¢ä½ç½®ã®å¤‰åŒ–を監視ã—ã¾ã™ã€‚ + +### 例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +地ç†ä½ç½®æƒ…å ± `ã®ä½ç½®` ã®æ¤œç´¢ã‚’カスタマイズã™ã‚‹ãŸã‚ã®çœç•¥å¯èƒ½ãªãƒ‘ラメーター. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### オプション + +* **enableHighAccuracy**: 最高ã®çµæžœãŒã€ã‚¢ãƒ—リケーションã«å¿…è¦ãŒã‚ã‚‹ã“ã¨ã®ãƒ’ントを示ã—ã¾ã™ã€‚ 既定ã§ã¯ã€ãƒ‡ãƒã‚¤ã‚¹ã®å–得を試ã¿ã¾ã™ã€ `Position` ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ ベースã®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’使用ã—ã¾ã™ã€‚ ã“ã®ãƒ—ãƒãƒ‘ティをè¨å®šã™ã‚‹ `true` 衛星測ä½ãªã©ã®ã‚ˆã‚Šæ£ç¢ºãªæ–¹æ³•を使用ã™ã‚‹ãŸã‚ã«ãƒ•ãƒ¬ãƒ¼ãƒ ãƒ¯ãƒ¼ã‚¯ã«æŒ‡ç¤ºã—ã¾ã™ã€‚ *(ブール値)* + +* **タイムアウト**: ã¸ã®å‘¼ã³å‡ºã—ã‹ã‚‰é€šéŽãŒè¨±å¯ã•れる時間 (ミリ秒å˜ä½) ã®æœ€å¤§é•· `navigator.geolocation.getCurrentPosition` ã¾ãŸã¯ `geolocation.watchPosition` ã¾ã§å¯¾å¿œã™ã‚‹ã€ `geolocationSuccess` コールãƒãƒƒã‚¯ã‚’実行ã—ã¾ã™ã€‚ å ´åˆã¯ã€ `geolocationSuccess` ã“ã®æ™‚間内ã«ã€ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã¯å‘¼ã³å‡ºã•れã¾ã›ã‚“〠`geolocationError` コールãƒãƒƒã‚¯ã«æ¸¡ã•れる〠`PositionError.TIMEOUT` ã®ã‚¨ãƒ©ãƒ¼ コード。 (ã¨çµ„ã¿åˆã‚ã›ã¦ä½¿ç”¨ã™ã‚‹ã¨ãã«æ³¨æ„ã—ã¦ãã ã•ã„ `geolocation.watchPosition` ã® `geolocationError` é–“éš”ã§ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯ã‚’呼ã³å‡ºã™ã“ã¨ãŒã§ãã¾ã™ã™ã¹ã¦ `timeout` ミリ秒 ï¼)*(æ•°)* + +* **maximumAge**: å¹´é½¢ãŒã‚るミリ秒å˜ä½ã§æŒ‡å®šã—ãŸæ™‚間よりも大ãããªã„ã‚ャッシュã•れãŸä½ç½®ã‚’å—ã‘入れã¾ã™ã€‚*(æ•°)* + +### Android ã®ç™– + +`enableHighAccuracy` オプション㌠`true` ã«è¨å®šã—ãªã„é™ã‚Šã€ã‚¢ãƒ³ãƒ‰ãƒã‚¤ãƒ‰ 2.x エミュレーター地ç†ä½ç½®æƒ…å ±ã®çµæžœã‚’è¿”ã•ãªã„. + +## navigator.geolocation.clearWatch + +`watchID` パラメーターã«ã‚ˆã£ã¦å‚ç…§ã•れるã€ãƒ‡ãƒã‚¤ã‚¹ã®å ´æ‰€ã¸ã®å¤‰æ›´ã‚’見ã¦åœæ¢ã—ã¾ã™ã€‚ + + navigator.geolocation.clearWatch(watchID); + + +### パラメーター + +* **watchID**: ã® id〠`watchPosition` をクリアã™ã‚‹é–“隔。(æ–‡å—列) + +### 例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 座標ã¨åœ°ç†ä½ç½®æƒ…å ± API ã§ä½œæˆã•れãŸã‚¿ã‚¤ãƒ スタンプãŒå«ã¾ã‚Œã¾ã™ã€‚ + +### プãƒãƒ‘ティ + +* **coords**: 地ç†çš„座標ã®ã‚»ãƒƒãƒˆã€‚*(座標)* + +* **timestamp**: 作æˆã®ã‚¿ã‚¤ãƒ スタンプを `coords` 。*(日)* + +## Coordinates + +`Coordinates` ã®ã‚ªãƒ–ジェクトã¯ç¾åœ¨ã®ä½ç½®ã®ãŸã‚ã®è¦æ±‚ã§ã‚³ãƒ¼ãƒ«ãƒãƒƒã‚¯é–¢æ•°ã«ä½¿ç”¨ã™ã‚‹ `Position` オブジェクトã«ã‚¢ã‚¿ãƒƒãƒã•れã¾ã™ã€‚ ä½ç½®ã®åœ°ç†åº§æ¨™ã‚’記述ã™ã‚‹ãƒ—ãƒãƒ‘ティã®ã‚»ãƒƒãƒˆãŒå«ã¾ã‚Œã¦ã„ã¾ã™ã€‚ + +### プãƒãƒ‘ティ + +* **latitude**: 10 度緯度。*(æ•°)* + +* **longitude**: 10 進度ã®çµŒåº¦ã€‚*(æ•°)* + +* **altitude**: 楕円体上ã®ãƒ¡ãƒ¼ãƒˆãƒ«ã®ä½ç½®ã®é«˜ã•。*(æ•°)* + +* **accuracy**: メートルã®ç·¯åº¦ã¨çµŒåº¦åº§æ¨™ã®ç²¾åº¦ãƒ¬ãƒ™ãƒ«ã€‚*(æ•°)* + +* **altitudeAccuracy**: メートルã®é«˜åº¦åº§æ¨™ã®ç²¾åº¦ãƒ¬ãƒ™ãƒ«ã€‚*(æ•°)* + +* **headingã—**: 進行方å‘ã€ã‚«ã‚¦ãƒ³ãƒˆã€çœŸåŒ—ã‹ã‚‰æ™‚計回りã®è§’åº¦ã§æŒ‡å®šã—ã¾ã™ã€‚*(æ•°)* + +* **speed**: æ¯Žç§’ãƒ¡ãƒ¼ãƒˆãƒ«ã§æŒ‡å®šã•れãŸãƒ‡ãƒã‚¤ã‚¹ã®ç¾åœ¨ã®å¯¾åœ°é€Ÿåº¦ã€‚*(æ•°)* + +### ã‚¢ãƒžã‚¾ãƒ³ç« OS ç™– + +**altitudeAccuracy**: `null` ã‚’è¿”ã™ã“ã¨ã® Android デãƒã‚¤ã‚¹ã§ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“. + +### Android ã®ç™– + +**altitudeAccuracy**: `null` ã‚’è¿”ã™ã“ã¨ã® Android デãƒã‚¤ã‚¹ã§ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“. + +## PositionError + +`PositionError` オブジェクト navigator.geolocation ã§ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ãŸã¨ãã« `geolocationError` コールãƒãƒƒã‚¯é–¢æ•°ã«æ¸¡ã•れã¾ã™ã€‚ + +### プãƒãƒ‘ティ + +* **code**: 次ã®ã„ãšã‚Œã‹ã®å®šç¾©æ¸ˆã¿ã®ã‚¨ãƒ©ãƒ¼ コード。 + +* **message**: 発生ã—ãŸã‚¨ãƒ©ãƒ¼ã®è©³ç´°ã‚’説明ã™ã‚‹ã‚¨ãƒ©ãƒ¼ メッセージ。 + +### 定数 + +* `PositionError.PERMISSION_DENIED` + * ユーザーã®ä½ç½®æƒ…å ±ã‚’å–å¾—ã™ã‚‹ã‚¢ãƒ—リを許å¯ã—ãªã„å ´åˆã«è¿”ã•れã¾ã™ã€‚ã“れã¯ãƒ—ラットフォームã«ä¾å˜ã—ã¾ã™ã€‚ +* `PositionError.POSITION_UNAVAILABLE` + * デãƒã‚¤ã‚¹ãŒã€ä½ç½®ã‚’å–å¾—ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™è¿”ã•れã¾ã™ã€‚一般ã«ã€ã¤ã¾ã‚Šã€ãƒ‡ãƒã‚¤ã‚¹ãŒãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ã«æŽ¥ç¶šã•れã¦ã„ãªã„ã¾ãŸã¯è¡›æ˜Ÿã®ä¿®æ£ã‚’å¾—ã‚‹ã“ã¨ãŒã§ãã¾ã›ã‚“。 +* `PositionError.TIMEOUT` + * デãƒã‚¤ã‚¹ãŒã§æŒ‡å®šã•ã‚ŒãŸæ™‚間内ã®ä½ç½®ã‚’å–å¾—ã™ã‚‹ã“ã¨ãŒã§ãã‚‹ã¨ãã«è¿”ã•れる〠`timeout` ã«å«ã¾ã‚Œã¦ã„ã‚‹ `geolocationOptions` 。 使用ã™ã‚‹ã¨ `navigator.geolocation.watchPosition` ã€ã“ã®ã‚¨ãƒ©ãƒ¼ãŒç¹°ã‚Šè¿”ã—ã«æ¸¡ã™ã“ã¨ãŒã€ `geolocationError` コールãƒãƒƒã‚¯ã”㨠`timeout` (ミリ秒å˜ä½)。 diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ko/README.md new file mode 100644 index 00000000..1c032293 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ko/README.md @@ -0,0 +1,268 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +ì´ í”ŒëŸ¬ê·¸ì¸ ìœ„ë„ ë° ê²½ë„ ë“±ì˜ ì†Œìžì˜ ìœ„ì¹˜ì— ëŒ€ 한 ì •ë³´ë¥¼ ì œê³µí•©ë‹ˆë‹¤. ì¼ë°˜ì ì¸ ìœ„ì¹˜ ì •ë³´ 등 글로벌 í¬ì§€ì…”ë‹ ì‹œìŠ¤í…œ (GPS) ë° ìœ„ì¹˜ì™€ ê°™ì€ IP 주소, RFID, WiFi ë° ë¸”ë£¨íˆ¬ìŠ¤ MAC 주소 ë° GSM/CDMA ì…€ Id ë„¤íŠ¸ì›Œí¬ ì‹ í˜¸ì—서 ìœ ì¶” 합니다. ë³´ìž¥ì€ ì—†ë‹¤ëŠ” API 소ìžì˜ ì‹¤ì œ 위치를 반환 합니다. + +ì´ API [W3C Geolocation API 사양](http://dev.w3.org/geo/api/spec-source.html)ì— ê¸°ë°˜ 하 ê³ ì´ë¯¸ êµ¬í˜„ì„ ì œê³µ 하지 않는 장치ì—ë§Œ 실행 ë©ë‹ˆë‹¤. + +**ê²½ê³ **: 중요 한 ê°œì¸ ì •ë³´ 보호 ë¬¸ì œë¥¼ ì œê¸° 하는 위치 ì •ë³´ ë°ì´í„°ì˜ 수집 ë° ì‚¬ìš© 합니다. ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ê°œì¸ ì •ë³´ 보호 ì •ì±… 다른 당사ìžì™€ì˜ ë°ì´í„° (예를 들어, êµµê³ , ê´œ ì°® ì•„ ìš”, 우편 번호, 등)ì˜ ì •ë°€ë„ ìˆ˜ì¤€ì„ ê³µìœ ì—¬ë¶€ë¥¼ app 지리ì ë°ì´í„°ë¥¼ 사용 하는 방법 í† ë¡ í•´ì•¼ 한다. ê·¸ê²ƒì€ ì‚¬ìš©ìžì˜ í–‰ë°©ì„ ë°íž 수 있기 ë•Œë¬¸ì— ë° ì €ìž¥, ê·¸ë“¤ì˜ ì—¬í–‰ ì—사 지리ì 위치 ë°ì´í„°ëŠ” ì¼ë°˜ì 으로 민ê°í•œ 간주. ë”°ë¼ì„œ, ì• í”Œ 리 ì¼€ì´ ì…˜ì˜ ê°œì¸ ì •ë³´ 보호 ì •ì±… ë¿ë§Œ ì•„ë‹ˆë¼ ê°•ë ¥ 하 게 좋습니다 (해당 ë˜ëŠ” 경우 장치 ìš´ì˜ ì²´ì œ ì´ë ‡ê²Œ ì´ë¯¸ 하지 않는) ì‘ìš© 프로그램 위치 ì •ë³´ ë°ì´í„°ì— 액세스 하기 ì „ì— ê·¸ëƒ¥--시간 통지. ê·¸ 통지는 (예를 들어, **확ì¸** ë° **아니오**ì„ íƒ ì œì‹œ) 하 ì—¬ 사용ìžì˜ 허가 ì·¨ë“ ë¿ë§Œ 아니ë¼, 위ì—서 언급 ëœ ë™ì¼í•œ ì •ë³´ë¥¼ ì œê³µ 해야 합니다. ìžì„¸í•œ ë‚´ìš©ì€ ê°œì¸ ì •ë³´ 보호 ê°€ì´ë“œë¥¼ 참조 하ì‹ì‹œì˜¤. + +ì´ í”ŒëŸ¬ê·¸ì¸ (플랫í¼ì€ ê·¸ë ‡ì§€ 않으면 ëˆ„ë½ ëœ)ì— ëŒ€ 한 ì „ì— `navigator.geolocation` 개체를 ì •ì˜ í•©ë‹ˆë‹¤. + +개체가 ì „ì— ë²”ìœ„ì— ìžˆì§€ë§Œ,ì´ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ ì œê³µ ë˜ëŠ” 기능 하지 ì‚¬ìš©í• ìˆ˜ 있습니다까지 `deviceready` ì´ë²¤íЏ 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## 설치 + +코르ë„ë°” 5.0 + (현재 ì•ˆì •ì ì¸ 1.0.0) í•„ìš” + + cordova plugin add cordova-plugin-geolocation + + +코르ë„ë°”ì˜ ì´ì „ ë²„ì „ 사용 ë˜ì§€ 않는 id (부실 0.3.12)를 통해 ì„¤ì¹˜í• ìˆ˜ 있습니다. + + cordova plugin add org.apache.cordova.geolocation + + +ê·¸ê²ƒì€ ë˜í•œ ë°°ìƒ ê³„ì•½ urlì„ í†µí•´ ì§ì ‘ ì„¤ì¹˜í• ìˆ˜ (ë¶ˆì•ˆì •) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * Firefox ìš´ì˜ ì²´ì œ + * iOS + * Tizen + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + * 윈ë„ìš° + +## 메서드 + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## (ì½ê¸° ì „ìš©) 개체 + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +매개 변수 `Position` 개체와 `geolocationSuccess`를 디바ì´ìŠ¤ì˜ í˜„ìž¬ 위치를 반환합니다. 오류가 있는 경우ì—, `geolocationError` 콜백 `PositionError` ê°œì²´ì— ì „ë‹¬ ë©ë‹ˆë‹¤. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + + * **geolocationSuccess**: í˜„ìž¬ì˜ ìœ„ì¹˜ë¥¼ ì „ë‹¬ ë˜ëŠ” 콜백. + + * **geolocationError**: *(ì„ íƒ ì‚¬í•)* 오류가 ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. + + * **geolocationOptions**: *(ì„ íƒ ì‚¬í•)* 위치 옵션. + +### 예를 들어 + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +ìœ„ì¹˜ì— ë³€í™”ë¥¼ íƒì§€í• 때 소ìžì˜ 현재 위치를 반환 합니다. 장치 새 위치를 검색 하는 경우 `geolocationSuccess` 콜백 매개 변수로 개체를 `Position`으로 실행 합니다. 오류가 있는 경우ì—, `geolocationError` 콜백 매개 변수로 `PositionError` 개체를 실행 합니다. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + + * **geolocationSuccess**: í˜„ìž¬ì˜ ìœ„ì¹˜ë¥¼ ì „ë‹¬ ë˜ëŠ” 콜백. + + * **geolocationError**: (ì„ íƒ ì‚¬í•) 오류가 ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. + + * **geolocationOptions**: (ì„ íƒ ì‚¬í•)는 지리ì 위치 옵션. + +### 반환 + + * **문ìžì—´**: 시계 위치 ê°„ê²©ì„ ì°¸ì¡° 하는 시계 id를 반환 합니다. 시계 id와 함께 사용 해야 합니다 `navigator.geolocation.clearWatch` 위치 ë³€í™”ì— ëŒ€ 한 ë³´ê³ ì¤‘ì§€. + +### 예를 들어 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +지리ì `Position` ê²€ìƒ‰ì„ ì‚¬ìš©ìž ì§€ì • 하는 ì„ íƒì 매개 변수. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### 옵션 + + * **enableHighAccuracy**: 힌트는 ì‘ìš© í”„ë¡œê·¸ëž¨ì— í•„ìš”í•œ 최ìƒì˜ ê²°ê³¼ ì œê³µ 합니다. 기본ì 으로 장치를 검색 í•˜ë ¤ê³ í•œ `Position` ë„¤íŠ¸ì›Œí¬ ê¸°ë°˜ ë°©ë²•ì„ ì‚¬ìš© 하 ì—¬. ì´ ì†ì„±ì„ ì„¤ì • `true` 위성 위치 등 보다 ì •í™•í•œ ë°©ë²•ì„ ì‚¬ìš© 하 ì—¬ í”„ë ˆìž„ 워í¬. *(부울)* + + * **시간 ì œí•œ**: 최대 ì‹œê°„ì˜ ê¸¸ì´ (밀리초) 호출ì—서 ì „ë‹¬í• ìˆ˜ 있는 `navigator.geolocation.getCurrentPosition` ë˜ëŠ” `geolocation.watchPosition` 해당까지 `geolocationSuccess` 콜백 실행. 경우는 `geolocationSuccess` 콜백ì´ì´ 시간 ë‚´ì—서 호출 ë˜ì§€ 않습니다는 `geolocationError` 콜백 ì „ë‹¬ ë˜ëŠ” `PositionError.TIMEOUT` 오류 코드. (함께 사용 하는 경우 `geolocation.watchPosition` , `geolocationError` 콜백 간격ì—서 호출 ë 수 있는 ëª¨ë“ `timeout` 밀리초!) *(수)* + + * **maximumAge**: 밀리초 단위로 ì§€ì • ëœ ì‹œê°„ 보다 ë” í° ë˜ëŠ” ìºì‹œ 위치를 ìˆ˜ë½ í•©ë‹ˆë‹¤. *(수)* + +### 안 드 로ì´ë“œ 단ì + +`EnableHighAccuracy` ì˜µì…˜ì„ `true`로 ì„¤ì • ë˜ì–´ 있지 않으면 안 드 로ì´ë“œ 2.x ì—ë®¬ë ˆì´í„° 위치 ê²°ê³¼ 반환 하지 않는. + +## navigator.geolocation.clearWatch + +`watchID` 매개 변수ì—서 참조 하는 소ìžì˜ 위치 ë³€ê²½ì— ëŒ€ 한 ë³´ê³ ì¤‘ì§€ 합니다. + + navigator.geolocation.clearWatch(watchID); + + +### 매개 변수 + + * **watchID**: id는 `watchPosition` ê°„ê²©ì„ ì·¨ì†Œ 합니다. (문ìžì—´) + +### 예를 들어 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 좌표 ë° ì§€ë¦¬ì 위치 APIì— ì˜í•´ ìƒì„± 하는 타임 스탬프를 í¬í•¨ 합니다. + +### ì†ì„± + + * **coords**: 지리ì 좌표 ì§‘í•©. *(좌표)* + + * **timestamp**: ìƒì„± 타임 ìŠ¤íƒ¬í”„ì— ëŒ€ 한 `coords` . *(ë‚ ì§œ)* + +## Coordinates + +`Coordinates` 개체를 현재 ìœ„ì¹˜ì— ëŒ€ 한 ìš”ì²ì— 콜백 함수를 ì‚¬ìš©í• ìˆ˜ 있는 `Position` ê°œì²´ì— ì²¨ë¶€ ë©ë‹ˆë‹¤. ê·¸ê²ƒì€ ìœ„ì¹˜ì˜ ì§€ë¦¬ì 좌표를 설명 하는 ì†ì„± ì§‘í•©ì´ í¬í•¨ ë˜ì–´ 있습니다. + +### ì†ì„± + + * **latitude**: 소수ì ë„ ìœ„ë„. *(수)* + + * **longitude**: ê²½ë„ 10 진수 ê°ë„. *(수)* + + * **altitude**: 높ì´ì˜ íƒ€ì› ë©´ ë¯¸í„°ì— ìœ„ì¹˜. *(수)* + + * **ì •í™•ë„**: ì •í™•ë„ ë ˆë²¨ ë¯¸í„°ì— ìœ„ë„ ë° ê²½ë„ ì¢Œí‘œ. *(수)* + + * **altitudeAccuracy**: ë¯¸í„°ì— ê³ ë„ ì¢Œí‘œì˜ ì •í™•ë„ ìˆ˜ì¤€. *(수)* + + * **heading**: 여행, ì§„ ë¶ì„ 기준으로 시계 방향으로 세ë„ì— ì§€ì • ëœ ë°©í–¥ìœ¼ë¡œ. *(수)* + + * **speed**: 초당 ë¯¸í„°ì— ì§€ì • ëœ ë””ë°”ì´ìŠ¤ì˜ í˜„ìž¬ ë•… ì†ë„. *(수)* + +### 아마존 화재 OS 단ì + +**altitudeAccuracy**: `null` 반환 안 드 로ì´ë“œ ìž¥ì¹˜ì— ì˜í•´ ì§€ì› ë˜ì§€ 않습니다. + +### 안 드 로ì´ë“œ 단ì + +**altitudeAccuracy**: `null` 반환 안 드 로ì´ë“œ ìž¥ì¹˜ì— ì˜í•´ ì§€ì› ë˜ì§€ 않습니다. + +## PositionError + +`PositionError` 개체는 navigator.geolocation와 함께 오류가 ë°œìƒ í•˜ë©´ `geolocationError` 콜백 í•¨ìˆ˜ì— ì „ë‹¬ ë©ë‹ˆë‹¤. + +### ì†ì„± + + * **코드**: 미리 ì •ì˜ ëœ ì˜¤ë¥˜ 코드 중 하나가 ì•„ëž˜ì— ë‚˜ì—´ ëœ. + + * **message**: ë°œìƒ í•œ 오류 세부 ì •ë³´ë¥¼ 설명 하는 오류 메시지. + +### ìƒìˆ˜ + + * `PositionError.PERMISSION_DENIED` + * 사용ìžê°€ 위치 ì •ë³´ë¥¼ 검색 ì• í”Œ 리 ì¼€ì´ ì…˜ì„ í—ˆìš© 하지 않는 경우 반환 ë©ë‹ˆë‹¤. ì´ í”Œëž«í¼ì— ë”°ë¼ ë‹¬ë¼ ì§‘ë‹ˆë‹¤. + * `PositionError.POSITION_UNAVAILABLE` + * 장치 위치를 ê²€ìƒ‰í• ìˆ˜ ì—†ì„ ë•Œ 반환 합니다. ì¼ë°˜ì 으로,ì´ ìž¥ì¹˜ëŠ” 네트워í¬ì— ì—°ê²° ë˜ì–´ 있지 ì•Šì€ ë˜ëŠ” 위성 ìˆ˜ì • í”„ë¡œê·¸ëž¨ì„ ì–»ì„ ìˆ˜ 없습니다 ì˜ë¯¸ 합니다. + * `PositionError.TIMEOUT` + * ìž¥ì¹˜ì— ì§€ì • ëœ ì‹œê°„ ë‚´ì—서 위치를 ê²€ìƒ‰í• ìˆ˜ 없는 경우 반환 ë˜ëŠ” `timeout` ì— í¬í•¨ ëœ `geolocationOptions` . 함께 사용 ë 때 `navigator.geolocation.watchPosition` ,ì´ ì˜¤ë¥˜ë¥¼ 반복ì 으로 ì „ë‹¬ ë 수는 `geolocationError` 콜백 매 `timeout` 밀리초.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/ko/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ko/index.md new file mode 100644 index 00000000..2a3e7349 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ko/index.md @@ -0,0 +1,255 @@ +<!--- + 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-plugin-geolocation + +ì´ í”ŒëŸ¬ê·¸ì¸ ìœ„ë„ ë° ê²½ë„ ë“±ì˜ ì†Œìžì˜ ìœ„ì¹˜ì— ëŒ€ 한 ì •ë³´ë¥¼ ì œê³µí•©ë‹ˆë‹¤. ì¼ë°˜ì ì¸ ìœ„ì¹˜ ì •ë³´ 등 글로벌 í¬ì§€ì…”ë‹ ì‹œìŠ¤í…œ (GPS) ë° ìœ„ì¹˜ì™€ ê°™ì€ IP 주소, RFID, WiFi ë° ë¸”ë£¨íˆ¬ìŠ¤ MAC 주소 ë° GSM/CDMA ì…€ Id ë„¤íŠ¸ì›Œí¬ ì‹ í˜¸ì—서 ìœ ì¶” 합니다. ë³´ìž¥ì€ ì—†ë‹¤ëŠ” API 소ìžì˜ ì‹¤ì œ 위치를 반환 합니다. + +ì´ API [W3C Geolocation API 사양][1]ì— ê¸°ë°˜ 하 ê³ ì´ë¯¸ êµ¬í˜„ì„ ì œê³µ 하지 않는 장치ì—ë§Œ 실행 ë©ë‹ˆë‹¤. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**ê²½ê³ **: 중요 한 ê°œì¸ ì •ë³´ 보호 ë¬¸ì œë¥¼ ì œê¸° 하는 위치 ì •ë³´ ë°ì´í„°ì˜ 수집 ë° ì‚¬ìš© 합니다. ì‘ìš© í”„ë¡œê·¸ëž¨ì˜ ê°œì¸ ì •ë³´ 보호 ì •ì±… 다른 당사ìžì™€ì˜ ë°ì´í„° (예를 들어, êµµê³ , ê´œ ì°® ì•„ ìš”, 우편 번호, 등)ì˜ ì •ë°€ë„ ìˆ˜ì¤€ì„ ê³µìœ ì—¬ë¶€ë¥¼ app 지리ì ë°ì´í„°ë¥¼ 사용 하는 방법 í† ë¡ í•´ì•¼ 한다. ê·¸ê²ƒì€ ì‚¬ìš©ìžì˜ í–‰ë°©ì„ ë°íž 수 있기 ë•Œë¬¸ì— ë° ì €ìž¥, ê·¸ë“¤ì˜ ì—¬í–‰ ì—사 지리ì 위치 ë°ì´í„°ëŠ” ì¼ë°˜ì 으로 민ê°í•œ 간주. ë”°ë¼ì„œ, ì• í”Œ 리 ì¼€ì´ ì…˜ì˜ ê°œì¸ ì •ë³´ 보호 ì •ì±… ë¿ë§Œ ì•„ë‹ˆë¼ ê°•ë ¥ 하 게 좋습니다 (해당 ë˜ëŠ” 경우 장치 ìš´ì˜ ì²´ì œ ì´ë ‡ê²Œ ì´ë¯¸ 하지 않는) ì‘ìš© 프로그램 위치 ì •ë³´ ë°ì´í„°ì— 액세스 하기 ì „ì— ê·¸ëƒ¥--시간 통지. ê·¸ 통지는 (예를 들어, **확ì¸** ë° **아니오**ì„ íƒ ì œì‹œ) 하 ì—¬ 사용ìžì˜ 허가 ì·¨ë“ ë¿ë§Œ 아니ë¼, 위ì—서 언급 ëœ ë™ì¼í•œ ì •ë³´ë¥¼ ì œê³µ 해야 합니다. ìžì„¸í•œ ë‚´ìš©ì€ ê°œì¸ ì •ë³´ 보호 ê°€ì´ë“œë¥¼ 참조 하ì‹ì‹œì˜¤. + +ì´ í”ŒëŸ¬ê·¸ì¸ (플랫í¼ì€ ê·¸ë ‡ì§€ 않으면 ëˆ„ë½ ëœ)ì— ëŒ€ 한 ì „ì— `navigator.geolocation` 개체를 ì •ì˜ í•©ë‹ˆë‹¤. + +개체가 ì „ì— ë²”ìœ„ì— ìžˆì§€ë§Œ,ì´ í”ŒëŸ¬ê·¸ì¸ì— ì˜í•´ ì œê³µ ë˜ëŠ” 기능 하지 ì‚¬ìš©í• ìˆ˜ 있습니다까지 `deviceready` ì´ë²¤íЏ 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## 설치 + + cordova plugin add cordova-plugin-geolocation + + +## ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* Firefox ìš´ì˜ ì²´ì œ +* iOS +* Tizen +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +## 메서드 + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## (ì½ê¸° ì „ìš©) 개체 + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +매개 변수 `Position` 개체와 `geolocationSuccess`를 디바ì´ìŠ¤ì˜ í˜„ìž¬ 위치를 반환합니다. 오류가 있는 경우ì—, `geolocationError` 콜백 `PositionError` ê°œì²´ì— ì „ë‹¬ ë©ë‹ˆë‹¤. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + +* **geolocationSuccess**: í˜„ìž¬ì˜ ìœ„ì¹˜ë¥¼ ì „ë‹¬ ë˜ëŠ” 콜백. + +* **geolocationError**: *(ì„ íƒ ì‚¬í•)* 오류가 ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. + +* **geolocationOptions**: *(ì„ íƒ ì‚¬í•)* 위치 옵션. + +### 예를 들어 + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +ìœ„ì¹˜ì— ë³€í™”ë¥¼ íƒì§€í• 때 소ìžì˜ 현재 위치를 반환 합니다. 장치 새 위치를 검색 하는 경우 `geolocationSuccess` 콜백 매개 변수로 개체를 `Position`으로 실행 합니다. 오류가 있는 경우ì—, `geolocationError` 콜백 매개 변수로 `PositionError` 개체를 실행 합니다. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + +* **geolocationSuccess**: í˜„ìž¬ì˜ ìœ„ì¹˜ë¥¼ ì „ë‹¬ ë˜ëŠ” 콜백. + +* **geolocationError**: (ì„ íƒ ì‚¬í•) 오류가 ë°œìƒ í•˜ë©´ 실행 ë˜ëŠ” 콜백. + +* **geolocationOptions**: (ì„ íƒ ì‚¬í•)는 지리ì 위치 옵션. + +### 반환 + +* **문ìžì—´**: 시계 위치 ê°„ê²©ì„ ì°¸ì¡° 하는 시계 id를 반환 합니다. 시계 id와 함께 사용 해야 합니다 `navigator.geolocation.clearWatch` 위치 ë³€í™”ì— ëŒ€ 한 ë³´ê³ ì¤‘ì§€. + +### 예를 들어 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +지리ì `Position` ê²€ìƒ‰ì„ ì‚¬ìš©ìž ì§€ì • 하는 ì„ íƒì 매개 변수. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### 옵션 + +* **enableHighAccuracy**: 힌트는 ì‘ìš© í”„ë¡œê·¸ëž¨ì— í•„ìš”í•œ 최ìƒì˜ ê²°ê³¼ ì œê³µ 합니다. 기본ì 으로 장치를 검색 í•˜ë ¤ê³ í•œ `Position` ë„¤íŠ¸ì›Œí¬ ê¸°ë°˜ ë°©ë²•ì„ ì‚¬ìš© 하 ì—¬. ì´ ì†ì„±ì„ ì„¤ì • `true` 위성 위치 등 보다 ì •í™•í•œ ë°©ë²•ì„ ì‚¬ìš© 하 ì—¬ í”„ë ˆìž„ 워í¬. *(부울)* + +* **시간 ì œí•œ**: 최대 ì‹œê°„ì˜ ê¸¸ì´ (밀리초) 호출ì—서 ì „ë‹¬í• ìˆ˜ 있는 `navigator.geolocation.getCurrentPosition` ë˜ëŠ” `geolocation.watchPosition` 해당까지 `geolocationSuccess` 콜백 실행. 경우는 `geolocationSuccess` 콜백ì´ì´ 시간 ë‚´ì—서 호출 ë˜ì§€ 않습니다는 `geolocationError` 콜백 ì „ë‹¬ ë˜ëŠ” `PositionError.TIMEOUT` 오류 코드. (함께 사용 하는 경우 `geolocation.watchPosition` , `geolocationError` 콜백 간격ì—서 호출 ë 수 있는 ëª¨ë“ `timeout` 밀리초!) *(수)* + +* **maximumAge**: 밀리초 단위로 ì§€ì • ëœ ì‹œê°„ 보다 ë” í° ë˜ëŠ” ìºì‹œ 위치를 ìˆ˜ë½ í•©ë‹ˆë‹¤. *(수)* + +### 안 드 로ì´ë“œ 단ì + +`EnableHighAccuracy` ì˜µì…˜ì„ `true`로 ì„¤ì • ë˜ì–´ 있지 않으면 안 드 로ì´ë“œ 2.x ì—ë®¬ë ˆì´í„° 위치 ê²°ê³¼ 반환 하지 않는. + +## navigator.geolocation.clearWatch + +`watchID` 매개 변수ì—서 참조 하는 소ìžì˜ 위치 ë³€ê²½ì— ëŒ€ 한 ë³´ê³ ì¤‘ì§€ 합니다. + + navigator.geolocation.clearWatch(watchID); + + +### 매개 변수 + +* **watchID**: id는 `watchPosition` ê°„ê²©ì„ ì·¨ì†Œ 합니다. (문ìžì—´) + +### 예를 들어 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 좌표 ë° ì§€ë¦¬ì 위치 APIì— ì˜í•´ ìƒì„± 하는 타임 스탬프를 í¬í•¨ 합니다. + +### ì†ì„± + +* **coords**: 지리ì 좌표 ì§‘í•©. *(좌표)* + +* **timestamp**: ìƒì„± 타임 ìŠ¤íƒ¬í”„ì— ëŒ€ 한 `coords` . *(ë‚ ì§œ)* + +## Coordinates + +`Coordinates` 개체를 현재 ìœ„ì¹˜ì— ëŒ€ 한 ìš”ì²ì— 콜백 함수를 ì‚¬ìš©í• ìˆ˜ 있는 `Position` ê°œì²´ì— ì²¨ë¶€ ë©ë‹ˆë‹¤. ê·¸ê²ƒì€ ìœ„ì¹˜ì˜ ì§€ë¦¬ì 좌표를 설명 하는 ì†ì„± ì§‘í•©ì´ í¬í•¨ ë˜ì–´ 있습니다. + +### ì†ì„± + +* **latitude**: 소수ì ë„ ìœ„ë„. *(수)* + +* **longitude**: ê²½ë„ 10 진수 ê°ë„. *(수)* + +* **altitude**: 높ì´ì˜ íƒ€ì› ë©´ ë¯¸í„°ì— ìœ„ì¹˜. *(수)* + +* **ì •í™•ë„**: ì •í™•ë„ ë ˆë²¨ ë¯¸í„°ì— ìœ„ë„ ë° ê²½ë„ ì¢Œí‘œ. *(수)* + +* **altitudeAccuracy**: ë¯¸í„°ì— ê³ ë„ ì¢Œí‘œì˜ ì •í™•ë„ ìˆ˜ì¤€. *(수)* + +* **heading**: 여행, ì§„ ë¶ì„ 기준으로 시계 방향으로 세ë„ì— ì§€ì • ëœ ë°©í–¥ìœ¼ë¡œ. *(수)* + +* **speed**: 초당 ë¯¸í„°ì— ì§€ì • ëœ ë””ë°”ì´ìŠ¤ì˜ í˜„ìž¬ ë•… ì†ë„. *(수)* + +### 아마존 화재 OS 단ì + +**altitudeAccuracy**: `null` 반환 안 드 로ì´ë“œ ìž¥ì¹˜ì— ì˜í•´ ì§€ì› ë˜ì§€ 않습니다. + +### 안 드 로ì´ë“œ 단ì + +**altitudeAccuracy**: `null` 반환 안 드 로ì´ë“œ ìž¥ì¹˜ì— ì˜í•´ ì§€ì› ë˜ì§€ 않습니다. + +## PositionError + +`PositionError` 개체는 navigator.geolocation와 함께 오류가 ë°œìƒ í•˜ë©´ `geolocationError` 콜백 í•¨ìˆ˜ì— ì „ë‹¬ ë©ë‹ˆë‹¤. + +### ì†ì„± + +* **code**: 미리 ì •ì˜ ëœ ì˜¤ë¥˜ 코드 중 하나가 ì•„ëž˜ì— ë‚˜ì—´ ëœ. + +* **message**: ë°œìƒ í•œ 오류 세부 ì •ë³´ë¥¼ 설명 하는 오류 메시지. + +### ìƒìˆ˜ + +* `PositionError.PERMISSION_DENIED` + * 사용ìžê°€ 위치 ì •ë³´ë¥¼ 검색 ì• í”Œ 리 ì¼€ì´ ì…˜ì„ í—ˆìš© 하지 않는 경우 반환 ë©ë‹ˆë‹¤. ì´ í”Œëž«í¼ì— ë”°ë¼ ë‹¬ë¼ ì§‘ë‹ˆë‹¤. +* `PositionError.POSITION_UNAVAILABLE` + * 장치 위치를 ê²€ìƒ‰í• ìˆ˜ ì—†ì„ ë•Œ 반환 합니다. ì¼ë°˜ì 으로,ì´ ìž¥ì¹˜ëŠ” 네트워í¬ì— ì—°ê²° ë˜ì–´ 있지 ì•Šì€ ë˜ëŠ” 위성 ìˆ˜ì • í”„ë¡œê·¸ëž¨ì„ ì–»ì„ ìˆ˜ 없습니다 ì˜ë¯¸ 합니다. +* `PositionError.TIMEOUT` + * ìž¥ì¹˜ì— ì§€ì • ëœ ì‹œê°„ ë‚´ì—서 위치를 ê²€ìƒ‰í• ìˆ˜ 없는 경우 반환 ë˜ëŠ” `timeout` ì— í¬í•¨ ëœ `geolocationOptions` . 함께 사용 ë 때 `navigator.geolocation.watchPosition` ,ì´ ì˜¤ë¥˜ë¥¼ 반복ì 으로 ì „ë‹¬ ë 수는 `geolocationError` 콜백 매 `timeout` 밀리초. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/pl/README.md new file mode 100644 index 00000000..8d6717fd --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/pl/README.md @@ -0,0 +1,268 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Ten plugin zawiera informacje o lokalizacji urzÄ…dzenia, takie jak szerokość i dÅ‚ugość geograficznÄ…. NajczÄ™stsze źródÅ‚a informacji o lokalizacji obejmujÄ… Global Positioning System (GPS) i lokalizacji wywnioskować z sieci sygnaÅ‚y, takie jak adres IP, RFID, WiFi i Bluetooth MAC adresy, a komórki GSM/CDMA identyfikatorów. Nie ma żadnej gwarancji, że API zwraca rzeczywistej lokalizacji urzÄ…dzenia. + +Ten interfejs API jest oparty na [Specyfikacji W3C Geolocation API](http://dev.w3.org/geo/api/spec-source.html)i tylko wykonuje na urzÄ…dzeniach, które już nie zapewniajÄ… implementacja. + +**Ostrzeżenie**: zbierania i wykorzystywania danych geolokacyjnych podnosi kwestie prywatnoÅ›ci ważne. Polityka prywatnoÅ›ci danej aplikacji należy omówić, jak aplikacja używa danych, czy jest on dzielony z innych stron i poziom dokÅ‚adnoÅ›ci danych (na przykÅ‚ad, gruba, porzÄ…dku, kod pocztowy poziom, itp.). Danych geolokacyjnych ogólnie uznaje wrażliwych, bo to może ujawnić pobytu użytkownika i, jeÅ›li przechowywane, historii ich podróży. W zwiÄ…zku z tym oprócz aplikacji prywatnoÅ›ci, zdecydowanie warto powiadomienia just-in-time, zanim aplikacja uzyskuje dostÄ™p do danych (jeÅ›li urzÄ…dzenie system operacyjny nie robi już). Å»e ogÅ‚oszenie powinno zawierać te same informacje, o których wspomniano powyżej, jak również uzyskanie uprawnienia użytkownika (np. poprzez przedstawianie wyborów **OK** i **Nie dziÄ™ki**). Aby uzyskać wiÄ™cej informacji zobacz przewodnik prywatnoÅ›ci. + +Ten plugin definiuje obiekt globalny `navigator.geolocation` (dla platformy gdzie to inaczej brak). + +Mimo, że obiekt jest w globalnym zasiÄ™gu, funkcji oferowanych przez ten plugin nie sÄ… dostÄ™pne dopiero po turnieju `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Instalacja + +Wymaga to cordova 5.0 + (bieżącej stabilnej 1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +Starsze wersje cordova nadal można zainstalować za pomocÄ… niezalecany identyfikator (starych 0.3.12) + + cordova plugin add org.apache.cordova.geolocation + + +Jest również możliwość instalacji za poÅ›rednictwem repo url bezpoÅ›rednio (niestabilny) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + * Windows + +## Metody + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Obiekty (tylko do odczytu) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Zwraca bieżącÄ… pozycjÄ™ urzÄ…dzenia do `geolocationSuccess` wywoÅ‚anie zwrotne z `Position` obiektu jako parametr. JeÅ›li wystÄ™puje błąd, wywoÅ‚ania zwrotnego `geolocationError` jest przekazywany obiekt `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + + * **geolocationSuccess**: wywoÅ‚ania zwrotnego, który jest przekazywany aktualnej pozycji. + + * **geolocationError**: *(opcjonalne)* wywoÅ‚ania zwrotnego, która wykonuje w przypadku wystÄ…pienia błędu. + + * **geolocationOptions**: *(opcjonalne)* opcji geolokalizacji. + +### PrzykÅ‚ad + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Zwraca bieżącÄ… pozycjÄ™ urzÄ…dzenia po wykryciu zmiany pozycji. Gdy urzÄ…dzenie pobiera nowÄ… lokalizacjÄ™, wywoÅ‚ania zwrotnego `geolocationSuccess` wykonuje siÄ™ z `Position` obiektu jako parametr. JeÅ›li wystÄ™puje błąd, wywoÅ‚ania zwrotnego `geolocationError` wykonuje siÄ™ z obiektem `PositionError` jako parametr. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + + * **geolocationSuccess**: wywoÅ‚ania zwrotnego, który jest przekazywany aktualnej pozycji. + + * **geolocationError**: (opcjonalne) wywoÅ‚ania zwrotnego, która wykonuje w przypadku wystÄ…pienia błędu. + + * **geolocationOptions**: (opcjonalne) geolocation opcje. + +### Zwraca + + * **Napis**: zwraca identyfikator zegarek, który odwoÅ‚uje siÄ™ oglÄ…dać pozycji interwaÅ‚. Identyfikator zegarek powinny być używane z `navigator.geolocation.clearWatch` Aby przestać oglÄ…dać do zmiany pozycji. + +### PrzykÅ‚ad + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametry opcjonalne dostosować pobierania geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opcje + + * **enableHighAccuracy**: stanowi wskazówkÄ™, że aplikacja musi możliwie najlepszych rezultatów. DomyÅ›lnie, urzÄ…dzenie próbuje pobrać `Position` przy użyciu metody oparte na sieci. Ustawienie tej wÅ‚aÅ›ciwoÅ›ci na `true` mówi ramach dokÅ‚adniejszych metod, takich jak pozycjonowanie satelitarne. *(Wartość logiczna)* + + * **Limit czasu**: maksymalna dÅ‚ugość czas (w milisekundach), który może przekazać wywoÅ‚anie `navigator.geolocation.getCurrentPosition` lub `geolocation.watchPosition` do odpowiednich `geolocationSuccess` wykonuje wywoÅ‚anie zwrotne. JeÅ›li `geolocationSuccess` wywoÅ‚ania zwrotnego nie jest wywoÅ‚ywany w tej chwili, `geolocationError` wywoÅ‚ania zwrotnego jest przekazywany `PositionError.TIMEOUT` kod błędu. (Należy zauważyć, że w połączeniu z `geolocation.watchPosition` , `geolocationError` wywoÅ‚ania zwrotnego można nazwać w odstÄ™pie co `timeout` milisekund!) *(Liczba)* + + * **maximumAge**: przyjąć buforowane pozycji, w których wiek jest nie wiÄ™ksza niż okreÅ›lony czas w milisekundach. *(Liczba)* + +### Dziwactwa Androida + +Emulatory Androida 2.x nie zwracajÄ… wynik geolocation, chyba że opcja `enableHighAccuracy` jest ustawiona na `wartość true`. + +## navigator.geolocation.clearWatch + +Przestać oglÄ…dać zmiany poÅ‚ożenia urzÄ…dzenia okreÅ›lany przez parametr `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametry + + * **watchID**: identyfikator `watchPosition` InterwaÅ‚ jasne. (String) + +### PrzykÅ‚ad + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Zawiera współrzÄ™dne `Position` i sygnatury czasowej, stworzony przez geolocation API. + +### WÅ‚aÅ›ciwoÅ›ci + + * **coords**: zestaw współrzÄ™dnych geograficznych. *(WspółrzÄ™dne)* + + * **timestamp**: Sygnatura czasowa utworzenia dla `coords` . *(Data)* + +## Coordinates + +`Coordinates` obiektu jest dołączone do `Position` obiektu, który jest dostÄ™pny dla funkcji wywoÅ‚ania zwrotnego w proÅ›by o aktualnej pozycji. Zawiera zestaw wÅ‚aÅ›ciwoÅ›ci, które opisujÄ… geograficzne współrzÄ™dne pozycji. + +### WÅ‚aÅ›ciwoÅ›ci + + * **szerokość geograficzna**: Latitude w stopniach dziesiÄ™tnych. *(Liczba)* + + * **dÅ‚ugość geograficzna**: dÅ‚ugość geograficzna w stopniach dziesiÄ™tnych. *(Liczba)* + + * **wysokość**: wysokość pozycji metrów nad elipsoidalny. *(Liczba)* + + * **dokÅ‚adność**: poziom dokÅ‚adnoÅ›ci współrzÄ™dnych szerokoÅ›ci i dÅ‚ugoÅ›ci geograficznej w metrach. *(Liczba)* + + * **altitudeAccuracy**: poziom dokÅ‚adnoÅ›ci WspółrzÄ™dna wysokość w metrach. *(Liczba)* + + * **pozycja**: kierunek podróży, okreÅ›lonego w stopni liczÄ…c ruchu wskazówek zegara wzglÄ™dem północy rzeczywistej. *(Liczba)* + + * **prÄ™dkość**: Aktualna prÄ™dkość ziemi urzÄ…dzenia, okreÅ›lone w metrach na sekundÄ™. *(Liczba)* + +### Amazon ogieÅ„ OS dziwactwa + +**altitudeAccuracy**: nie obsÅ‚ugiwane przez Android urzÄ…dzeÅ„, zwracanie `wartoÅ›ci null`. + +### Dziwactwa Androida + +**altitudeAccuracy**: nie obsÅ‚ugiwane przez Android urzÄ…dzeÅ„, zwracanie `wartoÅ›ci null`. + +## PositionError + +`PositionError` obiekt jest przekazywany do funkcji wywoÅ‚ania zwrotnego `geolocationError`, gdy wystÄ…pi błąd z navigator.geolocation. + +### WÅ‚aÅ›ciwoÅ›ci + + * **Kod**: jeden z kodów błędów wstÄ™pnie zdefiniowanych poniżej. + + * **wiadomość**: komunikat o błędzie, opisujÄ…c szczegóły wystÄ…piÅ‚ błąd. + +### StaÅ‚e + + * `PositionError.PERMISSION_DENIED` + * Zwracane, gdy użytkownicy nie zezwalajÄ… aplikacji do pobierania informacji o pozycji. Jest to zależne od platformy. + * `PositionError.POSITION_UNAVAILABLE` + * Zwracane, gdy urzÄ…dzenie jest w stanie pobrać pozycji. Ogólnie rzecz biorÄ…c oznacza to urzÄ…dzenie nie jest podłączone do sieci lub nie może uzyskać satelita utrwalić. + * `PositionError.TIMEOUT` + * Zwracane, gdy urzÄ…dzenie jest w stanie pobrać pozycji w czasie okreÅ›lonym przez `timeout` w `geolocationOptions` . Gdy używana z `navigator.geolocation.watchPosition` , ten błąd może być wielokrotnie przekazywane do `geolocationError` zwrotne co `timeout` milisekund.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/pl/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/pl/index.md new file mode 100644 index 00000000..6d08320e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/pl/index.md @@ -0,0 +1,255 @@ +<!--- + 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-plugin-geolocation + +Ten plugin zawiera informacje o lokalizacji urzÄ…dzenia, takie jak szerokość i dÅ‚ugość geograficznÄ…. NajczÄ™stsze źródÅ‚a informacji o lokalizacji obejmujÄ… Global Positioning System (GPS) i lokalizacji wywnioskować z sieci sygnaÅ‚y, takie jak adres IP, RFID, WiFi i Bluetooth MAC adresy, a komórki GSM/CDMA identyfikatorów. Nie ma żadnej gwarancji, że API zwraca rzeczywistej lokalizacji urzÄ…dzenia. + +Ten interfejs API jest oparty na [Specyfikacji W3C Geolocation API][1]i tylko wykonuje na urzÄ…dzeniach, które już nie zapewniajÄ… implementacja. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Ostrzeżenie**: zbierania i wykorzystywania danych geolokacyjnych podnosi kwestie prywatnoÅ›ci ważne. Polityka prywatnoÅ›ci danej aplikacji należy omówić, jak aplikacja używa danych, czy jest on dzielony z innych stron i poziom dokÅ‚adnoÅ›ci danych (na przykÅ‚ad, gruba, porzÄ…dku, kod pocztowy poziom, itp.). Danych geolokacyjnych ogólnie uznaje wrażliwych, bo to może ujawnić pobytu użytkownika i, jeÅ›li przechowywane, historii ich podróży. W zwiÄ…zku z tym oprócz aplikacji prywatnoÅ›ci, zdecydowanie warto powiadomienia just-in-time, zanim aplikacja uzyskuje dostÄ™p do danych (jeÅ›li urzÄ…dzenie system operacyjny nie robi już). Å»e ogÅ‚oszenie powinno zawierać te same informacje, o których wspomniano powyżej, jak również uzyskanie uprawnienia użytkownika (np. poprzez przedstawianie wyborów **OK** i **Nie dziÄ™ki**). Aby uzyskać wiÄ™cej informacji zobacz przewodnik prywatnoÅ›ci. + +Ten plugin definiuje obiekt globalny `navigator.geolocation` (dla platformy gdzie to inaczej brak). + +Mimo, że obiekt jest w globalnym zasiÄ™gu, funkcji oferowanych przez ten plugin nie sÄ… dostÄ™pne dopiero po turnieju `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Instalacja + + cordova plugin add cordova-plugin-geolocation + + +## ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +## Metody + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Obiekty (tylko do odczytu) + +* Stanowisko +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Zwraca bieżącÄ… pozycjÄ™ urzÄ…dzenia do `geolocationSuccess` wywoÅ‚anie zwrotne z `Position` obiektu jako parametr. JeÅ›li wystÄ™puje błąd, wywoÅ‚ania zwrotnego `geolocationError` jest przekazywany obiekt `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + +* **geolocationSuccess**: wywoÅ‚ania zwrotnego, który jest przekazywany aktualnej pozycji. + +* **geolocationError**: *(opcjonalne)* wywoÅ‚ania zwrotnego, która wykonuje w przypadku wystÄ…pienia błędu. + +* **geolocationOptions**: *(opcjonalne)* opcji geolokalizacji. + +### PrzykÅ‚ad + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Zwraca bieżącÄ… pozycjÄ™ urzÄ…dzenia po wykryciu zmiany pozycji. Gdy urzÄ…dzenie pobiera nowÄ… lokalizacjÄ™, wywoÅ‚ania zwrotnego `geolocationSuccess` wykonuje siÄ™ z `Position` obiektu jako parametr. JeÅ›li wystÄ™puje błąd, wywoÅ‚ania zwrotnego `geolocationError` wykonuje siÄ™ z obiektem `PositionError` jako parametr. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + +* **geolocationSuccess**: wywoÅ‚ania zwrotnego, który jest przekazywany aktualnej pozycji. + +* **geolocationError**: (opcjonalne) wywoÅ‚ania zwrotnego, która wykonuje w przypadku wystÄ…pienia błędu. + +* **geolocationOptions**: (opcjonalne) geolocation opcje. + +### Zwraca + +* **Napis**: zwraca identyfikator zegarek, który odwoÅ‚uje siÄ™ oglÄ…dać pozycji interwaÅ‚. Identyfikator zegarek powinny być używane z `navigator.geolocation.clearWatch` Aby przestać oglÄ…dać do zmiany pozycji. + +### PrzykÅ‚ad + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametry opcjonalne dostosować pobierania geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opcje + +* **enableHighAccuracy**: stanowi wskazówkÄ™, że aplikacja musi możliwie najlepszych rezultatów. DomyÅ›lnie, urzÄ…dzenie próbuje pobrać `Position` przy użyciu metody oparte na sieci. Ustawienie tej wÅ‚aÅ›ciwoÅ›ci na `true` mówi ramach dokÅ‚adniejszych metod, takich jak pozycjonowanie satelitarne. *(Wartość logiczna)* + +* **Limit czasu**: maksymalna dÅ‚ugość czas (w milisekundach), który może przekazać wywoÅ‚anie `navigator.geolocation.getCurrentPosition` lub `geolocation.watchPosition` do odpowiednich `geolocationSuccess` wykonuje wywoÅ‚anie zwrotne. JeÅ›li `geolocationSuccess` wywoÅ‚ania zwrotnego nie jest wywoÅ‚ywany w tej chwili, `geolocationError` wywoÅ‚ania zwrotnego jest przekazywany `PositionError.TIMEOUT` kod błędu. (Należy zauważyć, że w połączeniu z `geolocation.watchPosition` , `geolocationError` wywoÅ‚ania zwrotnego można nazwać w odstÄ™pie co `timeout` milisekund!) *(Liczba)* + +* **maximumAge**: przyjąć buforowane pozycji, w których wiek jest nie wiÄ™ksza niż okreÅ›lony czas w milisekundach. *(Liczba)* + +### Dziwactwa Androida + +Emulatory Androida 2.x nie zwracajÄ… wynik geolocation, chyba że opcja `enableHighAccuracy` jest ustawiona na `wartość true`. + +## navigator.geolocation.clearWatch + +Przestać oglÄ…dać zmiany poÅ‚ożenia urzÄ…dzenia okreÅ›lany przez parametr `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametry + +* **watchID**: identyfikator `watchPosition` InterwaÅ‚ jasne. (String) + +### PrzykÅ‚ad + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Stanowisko + +Zawiera współrzÄ™dne `Position` i sygnatury czasowej, stworzony przez geolocation API. + +### WÅ‚aÅ›ciwoÅ›ci + +* **coords**: zestaw współrzÄ™dnych geograficznych. *(WspółrzÄ™dne)* + +* **sygnatura czasowa**: Sygnatura czasowa utworzenia dla `coords` . *(Data)* + +## Coordinates + +`Coordinates` obiektu jest dołączone do `Position` obiektu, który jest dostÄ™pny dla funkcji wywoÅ‚ania zwrotnego w proÅ›by o aktualnej pozycji. Zawiera zestaw wÅ‚aÅ›ciwoÅ›ci, które opisujÄ… geograficzne współrzÄ™dne pozycji. + +### WÅ‚aÅ›ciwoÅ›ci + +* **szerokość geograficzna**: Latitude w stopniach dziesiÄ™tnych. *(Liczba)* + +* **dÅ‚ugość geograficzna**: dÅ‚ugość geograficzna w stopniach dziesiÄ™tnych. *(Liczba)* + +* **wysokość**: wysokość pozycji metrów nad elipsoidalny. *(Liczba)* + +* **dokÅ‚adność**: poziom dokÅ‚adnoÅ›ci współrzÄ™dnych szerokoÅ›ci i dÅ‚ugoÅ›ci geograficznej w metrach. *(Liczba)* + +* **altitudeAccuracy**: poziom dokÅ‚adnoÅ›ci WspółrzÄ™dna wysokość w metrach. *(Liczba)* + +* **pozycja**: kierunek podróży, okreÅ›lonego w stopni liczÄ…c ruchu wskazówek zegara wzglÄ™dem północy rzeczywistej. *(Liczba)* + +* **prÄ™dkość**: Aktualna prÄ™dkość ziemi urzÄ…dzenia, okreÅ›lone w metrach na sekundÄ™. *(Liczba)* + +### Amazon ogieÅ„ OS dziwactwa + +**altitudeAccuracy**: nie obsÅ‚ugiwane przez Android urzÄ…dzeÅ„, zwracanie `wartoÅ›ci null`. + +### Dziwactwa Androida + +**altitudeAccuracy**: nie obsÅ‚ugiwane przez Android urzÄ…dzeÅ„, zwracanie `wartoÅ›ci null`. + +## PositionError + +`PositionError` obiekt jest przekazywany do funkcji wywoÅ‚ania zwrotnego `geolocationError`, gdy wystÄ…pi błąd z navigator.geolocation. + +### WÅ‚aÅ›ciwoÅ›ci + +* **Kod**: jeden z kodów błędów wstÄ™pnie zdefiniowanych poniżej. + +* **wiadomość**: komunikat o błędzie, opisujÄ…c szczegóły wystÄ…piÅ‚ błąd. + +### StaÅ‚e + +* `PositionError.PERMISSION_DENIED` + * Zwracane, gdy użytkownicy nie zezwalajÄ… aplikacji do pobierania informacji o pozycji. Jest to zależne od platformy. +* `PositionError.POSITION_UNAVAILABLE` + * Zwracane, gdy urzÄ…dzenie jest w stanie pobrać pozycji. Ogólnie rzecz biorÄ…c oznacza to urzÄ…dzenie nie jest podłączone do sieci lub nie może uzyskać satelita utrwalić. +* `PositionError.TIMEOUT` + * Zwracane, gdy urzÄ…dzenie jest w stanie pobrać pozycji w czasie okreÅ›lonym przez `timeout` w `geolocationOptions` . Gdy używana z `navigator.geolocation.watchPosition` , ten błąd może być wielokrotnie przekazywane do `geolocationError` zwrotne co `timeout` milisekund. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/ru/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ru/index.md new file mode 100644 index 00000000..3d9c766e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/ru/index.md @@ -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. +--> + +# cordova-plugin-geolocation + +Ðтот плагин предоÑтавлÑет информацию о меÑтоположении уÑтройÑтва, например, Широта и Долгота. Общие иÑточники информации о меÑтонахождении включают глобальной ÑиÑтемы Ð¿Ð¾Ð·Ð¸Ñ†Ð¸Ð¾Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ (GPS) и меÑтоположение, выведено из Ñети Ñигналов, таких как IP-адреÑ, RFID, WiFi и Bluetooth MAC-адреÑа и идентификаторы базовых Ñтанций Ñотовой GSM/CDMA. Ðет никакой гарантии, что API возвращает фактичеÑкое меÑтоположение уÑтройÑтва. + +Ðтот API оÑнован на [Спецификации W3C Geolocation API][1]и выполнÑетÑÑ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ на уÑтройÑтвах, которые уже не обеÑпечивают реализацию. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Предупреждение**: Ñбор и иÑпользование данных Ð³ÐµÐ¾Ð¿Ð¾Ð·Ð¸Ñ†Ð¸Ð¾Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¿Ð¾Ð´Ð½Ð¸Ð¼Ð°ÐµÑ‚ вопроÑÑ‹ важные конфиденциальноÑти. Политика конфиденциальноÑти вашего Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð´Ð¾Ð»Ð¶Ð½Ð° обÑудить, как приложение иÑпользует данные геопозиционированиÑ, ли она ÑовмеÑтно Ñ Ð´Ñ€ÑƒÐ³Ð¸Ð¼Ð¸ Ñторонами и уровень точноÑти данных (например, грубый, тонкий, почтовый Ð¸Ð½Ð´ÐµÐºÑ ÑƒÑ€Ð¾Ð²Ð½Ñ, Ñ‚.д.). Геолокации, как правило, ÑчитаетÑÑ ÐºÐ¾Ð½Ñ„Ð¸Ð´ÐµÐ½Ñ†Ð¸Ð°Ð»ÑŒÐ½Ð¾Ð¹, потому, что она может выÑвить меÑтонахождение Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¸, еÑли Ñохранены, иÑÑ‚Ð¾Ñ€Ð¸Ñ Ð¸Ñ… путешеÑтвиÑ. Таким образом помимо политики конфиденциальноÑти приложениÑ, Ñледует решительно раÑÑмотреть ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ just-in-time, прежде чем приложение обращаетÑÑ Ðº геолокации (еÑли операционной ÑиÑтемы уÑтройÑтва не так уже). Ðто уведомление должно обеÑпечивать ту же информацию, отметили выше, а также Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð¸Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ (например, путем предÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð²Ñ‹Ð±Ð¾Ñ€Ð° **OK** и **Ðет, ÑпаÑибо**). Ð”Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð¹ информации пожалуйÑта, Ñмотрите в руководÑтве конфиденциальноÑти. + +## УÑтановка + + cordova plugin add cordova-plugin-geolocation + + +## Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +## Методы + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Объекты (только Ð´Ð»Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Возвращает текущее положение уÑтройÑтва Ð´Ð»Ñ `geolocationSuccess` обратного вызова Ñ `Position` объект в качеÑтве параметра. ЕÑли еÑть ошибка, `geolocationError` обратного вызова передаетÑÑ `PositionError` объект. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Параметры + +* **geolocationSuccess**: обратный вызов, который передаетÑÑ Ð² текущей позиции. + +* **geolocationError**: *(необÑзательно)* обратного вызова, который выполнÑетÑÑ Ð¿Ñ€Ð¸ возникновении ошибки. + +* **geolocationOptions**: *(необÑзательно)* параметры геопозиционированиÑ. + +### Пример + + onSuccess обратного вызова / / Ñтот метод принимает позицию объекта, который Ñодержит / / текущие GPS координаты / / var onSuccess = function(position) {alert (' Широта: ' + position.coords.latitude + «\n» + ' Долгота: ' + position.coords.longitude + «\n» + ' Ð’Ñ‹Ñота: ' + position.coords.altitude + «\n» + ' точноÑть: ' + position.coords.accuracy + «\n» + ' выÑоте точноÑть: ' + position.coords.altitudeAccuracy + «\n» + ' заголовок: ' + position.coords.heading + «\n» + ' ÑкороÑть: ' + position.coords.speed + «\n» + ' штампа времени: ' + position.timestamp + «\n»);}; + + onError обратного вызова получает объект PositionError / / Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ onError(error) {alert (' код: ' + error.code + «\n» + ' Ñообщение: ' + error.message + «\n»);} + + navigator.geolocation.getCurrentPosition (onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Возвращает текущее положение уÑтройÑтва при обнаружении Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð² позиции. Когда уÑтройÑтво получает новое меÑто, `geolocationSuccess` обратного вызова выполнÑетÑÑ Ñ `Position` объект в качеÑтве параметра. ЕÑли еÑть ошибка, `geolocationError` обратного вызова выполнÑетÑÑ Ñ `PositionError` объект в качеÑтве параметра. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Параметры + +* **geolocationSuccess**: обратный вызов, который передаетÑÑ Ð² текущей позиции. + +* **geolocationError**: (необÑзательно) обратного вызова, который выполнÑетÑÑ Ð¿Ñ€Ð¸ возникновении ошибки. + +* **geolocationOptions**: параметры (необÑзательно) географичеÑкого раÑположениÑ. + +### Возвращает + +* **Строка**: Возвращает идентификатор чаÑÑ‹, ÑÑылаетÑÑ Ð½Ð° позицию интервала чаÑÑ‹. Идентификатор чаÑÑ‹ должны иÑпользоватьÑÑ Ñ `navigator.geolocation.clearWatch` прекратить Ñлежение за изменением в положении. + +### Пример + + onSuccess обратного вызова / / Ñтот метод принимает «Position» объект, который Ñодержит / / текущие GPS координаты / / Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ onSuccess(position) {var Ñлемент = document.getElementById('geolocation'); + element.innerHTML = ' Широта: ' + position.coords.latitude + ' < br / >' + ' Долгота: ' + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML; + } / / onError обратного вызова получает объект PositionError / / Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ onError(error) {alert (' код: ' + error.code + «\n» + ' Ñообщение: ' + error.message + «\n»);} + + Опции: БроÑьте Ñообщение об ошибке, еÑли обновление не получено каждые 30 Ñекунд. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, {тайм-аут: 30000}); + + +## geolocationOptions + +ÐеобÑзательные параметры Ð´Ð»Ñ Ð½Ð°Ñтройки поиÑка географичеÑкого раÑположениÑ`Position`. + + {maximumAge: 3000, тайм-аут: 5000, enableHighAccuracy: true}; + + +### Параметры + +* **enableHighAccuracy**: предоÑтавлÑет подÑказку, что приложению требуютÑÑ Ð½Ð°Ð¸Ð»ÑƒÑ‡ÑˆÐ¸Ðµ результаты. По умолчанию уÑтройÑтво пытаетÑÑ Ð¿Ð¾Ð»ÑƒÑ‡Ð¸Ñ‚ÑŒ `Position` Ñ Ð¸Ñпользованием методов на оÑнове Ñети. УÑтановка Ñтого ÑвойÑтва значение `true` указывает Ñреде иÑпользовать более точные методы, например Ñпутникового позиционированиÑ. *(ЛогичеÑкое значение)* + +* **Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ**: макÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð´Ð»Ð¸Ð½Ð° времени (в миллиÑекундах), которое может пройти от вызова `navigator.geolocation.getCurrentPosition` или `geolocation.watchPosition` до ÑоответÑтвующих `geolocationSuccess` выполнÑет обратный вызов. ЕÑли `geolocationSuccess` обратного вызова не вызываетÑÑ Ð² течение Ñтого времени, `geolocationError` обратного вызова передаетÑÑ `PositionError.TIMEOUT` код ошибки. (Обратите внимание, что при иÑпользовании в Ñочетании Ñ `geolocation.watchPosition` , `geolocationError` обратный вызов может быть вызван на интервале каждые `timeout` миллиÑекунд!) *(ЧиÑло)* + +* **maximumAge**: принÑть кÑшированное положение, возраÑÑ‚ которых не превышает указанного времени в миллиÑекундах. *(ЧиÑло)* + +### ОÑобенноÑти Android + +ÐмулÑторы Android 2.x не возвращать результат географичеÑкого раÑположениÑ, еÑли `enableHighAccuracy` параметр имеет значение`true`. + +## navigator.geolocation.clearWatch + +ОÑтановить проÑмотр Ð´Ð»Ñ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð¼ÐµÑÑ‚Ð¾Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ ÑƒÑтройÑтва ÑÑылаетÑÑ `watchID` параметр. + + navigator.geolocation.clearWatch(watchID); + + +### Параметры + +* **watchID**: идентификатор `watchPosition` интервал, чтобы очиÑтить. (Строка) + +### Пример + + Опции: наблюдать за изменениÑми в положении и иÑпользовать наиболее / / Ñ‚Ð¾Ñ‡Ð½Ð°Ñ Ð¿Ð¾Ð·Ð¸Ñ†Ð¸Ñ Ð¿Ñ€Ð¸Ð¾Ð±Ñ€ÐµÑ‚ÐµÐ½Ð¸Ðµ доÑтупным методом. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, {enableHighAccuracy: true}); + + .. .later на... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Содержит `Position` координат и отметок времени, ÑÐ¾Ð·Ð´Ð°Ð½Ð½Ð°Ñ API геопозиционированиÑ. + +### Параметры + +* **CoOrds**: набор географичеÑких координат. *(Координаты)* + +* **штамп времени**: штамп времени ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ð´Ð»Ñ `coords` . *(Дата)* + +## Coordinates + +A `Coordinates` объект приÑоединен к `Position` объект, который доÑтупен Ð´Ð»Ñ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾Ð³Ð¾ вызова функций в запроÑÑ‹ Ð´Ð»Ñ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ¹ позиции. Он Ñодержит набор ÑвойÑтв, которые опиÑывают географичеÑкие координаты позиции. + +### Параметры + +* **Широта**: Широта в деÑÑтичных градуÑах. *(ЧиÑло)* + +* **Долгота**: Долгота в деÑÑтичных градуÑах. *(ЧиÑло)* + +* **Ð’Ñ‹Ñота**: выÑота позиции в метрах над ÑллипÑоидом. *(ЧиÑло)* + +* **точноÑть**: уровень точноÑти координат широты и долготы в метрах. *(ЧиÑло)* + +* **altitudeAccuracy**: уровень точноÑти координат выÑоты в метрах. *(ЧиÑло)* + +* **заголовок**: направление движениÑ, указанный в градуÑах, ÑÑ‡Ð¸Ñ‚Ð°Ñ Ð¿Ð¾ чаÑовой Ñтрелке отноÑительно иÑтинного Ñевера. *(ЧиÑло)* + +* **ÑкороÑть**: Ð¢ÐµÐºÑƒÑ‰Ð°Ñ ÑкороÑть земли уÑтройÑтва, указанного в метрах в Ñекунду. *(ЧиÑло)* + +### ОÑобенноÑти Amazon Fire OS + +**altitudeAccuracy**: не поддерживаетÑÑ Android уÑтройÑтв, возвращаÑ`null`. + +### ОÑобенноÑти Android + +**altitudeAccuracy**: не поддерживаетÑÑ Android уÑтройÑтв, возвращаÑ`null`. + +## PositionError + +`PositionError`Объект передаетÑÑ Ð² `geolocationError` функции обратного вызова при возникновении ошибки Ñ navigator.geolocation. + +### Параметры + +* **code**: один из Ñтандартных кодов ошибок, перечиÑленных ниже. + +* **Ñообщение**: Ñообщение об ошибке Ñ Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ñ‹Ð¼Ð¸ ÑведениÑми об ошибке. + +### КонÑтанты + +* `PositionError.PERMISSION_DENIED` + * ВозвращаетÑÑ, когда пользователи не позволÑÑŽÑ‚ приложению получить ÑÐ²ÐµÐ´ÐµÐ½Ð¸Ñ Ð¾ положении. Ðто завиÑит от платформы. +* `PositionError.POSITION_UNAVAILABLE` + * ВозвращаетÑÑ, еÑли уÑтройÑтво не удаетÑÑ Ð¿Ð¾Ð»ÑƒÑ‡Ð¸Ñ‚ÑŒ позиции. Ð’ общем Ñто означает, что прибор не подключен к Ñети или не может получить Спутниковое иÑправить. +* `PositionError.TIMEOUT` + * ВозвращаетÑÑ, еÑли уÑтройÑтво не удаетÑÑ Ð¿Ð¾Ð»ÑƒÑ‡Ð¸Ñ‚ÑŒ позиции в течение времени, заданного параметром `timeout` в `geolocationOptions` . При иÑпользовании Ñ `navigator.geolocation.watchPosition` , Ñта ошибка может быть неоднократно передан `geolocationError` обратного вызова каждый `timeout` миллиÑекунд. diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/zh/README.md new file mode 100644 index 00000000..1ad9931e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/zh/README.md @@ -0,0 +1,268 @@ +<!-- +# license: 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-plugin-geolocation + +[](https://travis-ci.org/apache/cordova-plugin-geolocation) + +é€™å€‹å¤–æŽ›ç¨‹å¼æä¾›äº†æœ‰é—œè©²è¨å‚™çš„ä½ç½®ï¼Œä¾‹å¦‚緯度和經度資訊。 常見的ä½ç½®è³‡è¨Šä¾†æºåŒ…括全çƒå®šä½ç³»çµ± (GPS) 和網路信號,如 IP ä½å€ã€ RFID〠WiFi å’Œè—牙 MAC ä½å€å’Œ GSM/CDMA å„²å˜æ ¼ Id 從推斷出的ä½ç½®ã€‚ 沒有任何ä¿è‰ï¼ŒAPI 返回è¨å‚™çš„實際ä½ç½®ã€‚ + +æ¤ API 基於[W3C 地ç†å®šä½ API è¦ç¯„](http://dev.w3.org/geo/api/spec-source.html),並åªåŸ·è¡Œå·²ç¶“䏿供坦ç¾çš„è¨å‚™ä¸Šã€‚ + +**è¦å‘Š**: 地ç†å®šä½è³‡æ–™çš„æ”¶é›†å’Œä½¿ç”¨æå‡ºäº†é‡è¦çš„éš±ç§å•題。 您的應用程å¼çš„éš±ç§æ¬ŠåŽŸå‰‡æ‡‰è©²è¨Žè«–é€™æ¬¾æ‡‰ç”¨ç¨‹å¼å¦‚何使用地ç†å®šä½è³‡æ–™ï¼Œè³‡æ–™æ˜¯å¦å…±ç”¨å®ƒçš„ä»»ä½•å…¶ä»–ç· ç´„æ–¹å’Œçš„è³‡æ–™ (例如,粗〠細,ZIP 代碼級別,ç‰ç‰ï¼‰ 的精度水準。 地ç†å®šä½è³‡æ–™ä¸€èˆ¬èªç‚ºæ˜¯æ•æ„Ÿï¼Œå› ç‚ºå®ƒèƒ½æç¤ºä½¿ç”¨è€…的下è½ä»¥åŠå¦‚æžœå˜å„²ï¼Œä»–們的旅行的æ·å²ã€‚ å› æ¤ï¼Œé™¤äº†æ‡‰ç”¨ç¨‹å¼çš„éš±ç§æ¬ŠåŽŸå‰‡ï¼Œæ‚¨æ‡‰å¼·çƒˆè€ƒæ…®ä¹‹å‰æ‡‰ç”¨ç¨‹å¼è¨ªå•地ç†å®šä½è³‡æ–™ (如果è¨å‚™ä½œæ¥ç³»çµ±ä¸æœƒé€™æ¨£åšå·²ç¶“) æä¾›åœ¨æ™‚間的通知。 該通知應æä¾›ç›¸åŒçš„資訊上文指出的並ç²å–è©²ä½¿ç”¨è€…çš„è¨±å¯æ¬Š (例如,通éŽç‚º**確定**並**䏿„Ÿè¬**æå‡ºçš„鏿“‡ï¼‰ã€‚ 有關詳細資訊,請åƒé–±éš±ç§æŒ‡å—。 + +這個外掛程å¼å®šç¾©äº†ä¸€å€‹å…¨çƒ `navigator.geolocation` 物件 (為平臺哪裡å¦å‰‡ä¸Ÿå¤±ï¼‰ã€‚ + +儘管物件是在全çƒç¯„åœå…§ï¼Œæä¾›é€™å€‹å¤–掛程å¼çš„功能ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## å®‰è£ + +é€™å°±è¦æ±‚科爾多瓦 5.0 + (ç•¶å‰ç©©å®š v1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +舊版本的科爾多瓦ä»å¯ä»¥é€šéŽå·²æ£„用 id (陳舊 0.3.12) å®‰è£ + + cordova plugin add org.apache.cordova.geolocation + + +它也是å¯ä»¥ç›´æŽ¥é€šéŽå›žè³¼ url å®‰è£ (ä¸ç©©å®š) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + * iOS + * Tizen + * Windows Phone 7 å’Œ 8 + * Windows 8 + * Windows + +## 方法 + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## 物件 (唯讀) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +返回è¨å‚™çš„ç•¶å‰ä½ç½®åˆ° `geolocationSuccess` 回檔與 `Position` ç‰©ä»¶ä½œç‚ºåƒæ•¸ã€‚ 如果有錯誤,`geolocationError` 回檔傳éžä¸€å€‹ `PositionError` 物件。 + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### åƒæ•¸ + + * **geolocationSuccess**: 傳éžç•¶å‰ä½ç½®çš„回檔。 + + * **geolocationError**: *(å¯é¸ï¼‰*如果錯誤發生時執行的回檔。 + + * **geolocationOptions**: *(å¯é¸ï¼‰*地ç†å®šä½é¸é …。 + +### 示例 + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +返回è¨å‚™çš„ç•¶å‰çš„ä½ç½®ï¼Œç•¶æª¢æ¸¬åˆ°æ›´æ”¹ä½ç½®ã€‚ ç•¶è¨å‚™æª¢ç´¢ä¸€å€‹æ–°ä½ç½®æ™‚,則 `geolocationSuccess` 回檔執行與 `Position` ç‰©ä»¶ä½œç‚ºåƒæ•¸ã€‚ 如果有錯誤,則 `geolocationError` 回檔執行åŒä¸€å€‹ `PositionError` ç‰©ä»¶ä½œç‚ºåƒæ•¸ã€‚ + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### åƒæ•¸ + + * **geolocationSuccess**: 傳éžç•¶å‰ä½ç½®çš„回檔。 + + * **geolocationError**: (å¯é¸ï¼‰ 如果錯誤發生時執行的回檔。 + + * **geolocationOptions**: (å¯é¸ï¼‰ 地ç†å®šä½é¸é …。 + +### 返回 + + * **String**: 返回引用的觀看ä½ç½®é–“隔的表 id。 應與一起使用的表 id `navigator.geolocation.clearWatch` åœæ¢äº†è§€çœ‹ä¸ä½ç½®çš„æ›´æ”¹ã€‚ + +### 示例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +è‹¥è¦è‡ªè¨‚çš„åœ°ç† `Position` 檢索的å¯é¸åƒæ•¸. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### é¸é … + + * **enableHighAccuracy**: æä¾›æ‡‰ç”¨ç¨‹å¼éœ€è¦æœ€ä½³çš„å¯èƒ½çµæžœçš„æç¤ºã€‚ é è¨æƒ…æ³ä¸‹ï¼Œè©²è¨å‚™å°‡å˜—試檢索 `Position` 使用基於網路的方法。 å°‡æ¤å±¬æ€§è¨ç½®ç‚º `true` 告訴è¦ä½¿ç”¨æ›´ç²¾ç¢ºçš„æ–¹æ³•,如衛星定ä½çš„æ¡†æž¶ã€‚ *(布林值)* + + * **timeout**: 時間 (毫秒) 從調用傳éžï¼Œå…許的最大長度 `navigator.geolocation.getCurrentPosition` 或 `geolocation.watchPosition` 直到相應的 `geolocationSuccess` 回檔執行。 如果 `geolocationSuccess` 䏿œƒåœ¨æ¤æ™‚間內調用回檔 `geolocationError` 傳éžå›žæª” `PositionError.TIMEOUT` 錯誤代碼。 (請注æ„,與一起使用時 `geolocation.watchPosition` 〠`geolocationError` 的時間間隔å¯ä»¥èª¿ç”¨å›žæª”æ¯ `timeout` 毫秒!)*(人數)* + + * **maximumAge**: 接å—其年齡大於指定以毫秒為單ä½çš„æ™‚間沒有緩å˜çš„ä½ç½®ã€‚*(人數)* + +### Android 的怪癖 + +Android 2.x 模擬器ä¸é™¤éž `enableHighAccuracy` é¸é …è¨ç½®ç‚º `true`,å¦å‰‡è¿”回地ç†å®šä½çµæžœ. + +## navigator.geolocation.clearWatch + +åœæ¢è§€å¯Ÿåˆ° `watchID` åƒæ•¸æ‰€å¼•用的è¨å‚™çš„ä½ç½®ã€‚ + + navigator.geolocation.clearWatch(watchID); + + +### åƒæ•¸ + + * **watchID**: çš„ id `watchPosition` 清除的時間間隔。(å—串) + +### 示例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +åŒ…å« `Position` 座標和時間戳記,由地ç†ä½ç½® API 創建。 + +### 屬性 + + * **coords**: 一組的地ç†åº§æ¨™ã€‚*(座標)* + + * **timestamp**: 創建時間戳記為 `coords` 。*(日期)* + +## Coordinates + +`Coordinates` çš„ç‰©ä»¶é™„åŠ åˆ°ä¸€å€‹ `Position` 物件,å¯ç”¨æ–¼åœ¨ç•¶å‰è·ä½çš„請求ä¸çš„回呼函數。 它包å«ä¸€çµ„屬性æè¿°ä½ç½®çš„地ç†åº§æ¨™ã€‚ + +### 屬性 + + * **latitude**: 緯度以å進ä½åº¦ç‚ºå–®ä½ã€‚*(人數)* + + * **longitude**: 經度以å進ä½åº¦ç‚ºå–®ä½ã€‚*(人數)* + + * **altitude**: 高度在米以上橢çƒé«”ä¸çš„ä½ç½®ã€‚*(人數)* + + * **accuracy**: ä¸ç±³çš„緯度和經度座標的精度級別。*(人數)* + + * **altitudeAccuracy**: 在米的海拔高度座標的精度級別。*(人數)* + + * **heading**: 旅行,指定以度為單ä½å…ƒæ•¸ç›®ç›¸å°æ–¼çœŸåŒ—é †æ™‚é‡æ–¹å‘。*(人數)* + + * **speed**: ç•¶å‰åœ°é¢é€Ÿåº¦çš„è¨å‚™ï¼ŒæŒ‡å®šåœ¨ç±³æ¯ç§’。*(人數)* + +### 亞馬éœç« OS 怪癖 + +**altitudeAccuracy**: 䏿”¯æ´çš„ Android è¨å‚™ï¼Œè¿”回 `null`. + +### Android 的怪癖 + +**altitudeAccuracy**: 䏿”¯æ´çš„ Android è¨å‚™ï¼Œè¿”回 `null`. + +## PositionError + +`PositionError` 物件將傳éžçµ¦ `geolocationError` 回呼函數ä¸ï¼Œç•¶å‡ºç¾ navigator.geolocation 錯誤時發生。 + +### 屬性 + + * **code**: 下é¢åˆ—出的é 定義的錯誤代碼之一。 + + * **message**: æè¿°æ‰€é‡åˆ°çš„錯誤的詳細資訊的錯誤訊æ¯ã€‚ + +### å¸¸é‡ + + * `PositionError.PERMISSION_DENIED` + * 返回當使用者ä¸å…è¨±æ‡‰ç”¨ç¨‹å¼æª¢ç´¢çš„ä½ç½®è³‡è¨Šã€‚é€™æ˜¯å–æ±ºæ–¼å¹³è‡ºã€‚ + * `PositionError.POSITION_UNAVAILABLE` + * 返回è¨å‚™æ™‚,ä¸èƒ½æª¢ç´¢çš„ä½ç½®ã€‚一般情æ³ä¸‹ï¼Œé€™æ„味著該è¨å‚™æœªé€£æŽ¥åˆ°ç¶²è·¯æˆ–無法ç²å–衛星的修復。 + * `PositionError.TIMEOUT` + * 返回è¨å‚™æ™‚,無法在指定的時間內檢索ä½ç½® `timeout` ä¸åŒ…å« `geolocationOptions` 。 與一起使用時 `navigator.geolocation.watchPosition` ,æ¤éŒ¯èª¤å¯èƒ½å復傳éžçµ¦ `geolocationError` å›žæª”æ¯ `timeout` 毫秒為單ä½ï¼‰ã€‚
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/doc/zh/index.md b/StoneIsland/plugins/cordova-plugin-geolocation/doc/zh/index.md new file mode 100644 index 00000000..d6d831e7 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/doc/zh/index.md @@ -0,0 +1,255 @@ +<!--- + 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-plugin-geolocation + +é€™å€‹å¤–æŽ›ç¨‹å¼æä¾›äº†æœ‰é—œè©²è¨å‚™çš„ä½ç½®ï¼Œä¾‹å¦‚緯度和經度資訊。 常見的ä½ç½®è³‡è¨Šä¾†æºåŒ…括全çƒå®šä½ç³»çµ± (GPS) 和網路信號,如 IP ä½å€ã€ RFID〠WiFi å’Œè—牙 MAC ä½å€å’Œ GSM/CDMA å„²å˜æ ¼ Id 從推斷出的ä½ç½®ã€‚ 沒有任何ä¿è‰ï¼ŒAPI 返回è¨å‚™çš„實際ä½ç½®ã€‚ + +æ¤ API 基於[W3C 地ç†å®šä½ API è¦ç¯„][1],並åªåŸ·è¡Œå·²ç¶“䏿供坦ç¾çš„è¨å‚™ä¸Šã€‚ + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**è¦å‘Š**: 地ç†å®šä½è³‡æ–™çš„æ”¶é›†å’Œä½¿ç”¨æå‡ºäº†é‡è¦çš„éš±ç§å•題。 您的應用程å¼çš„éš±ç§æ¬ŠåŽŸå‰‡æ‡‰è©²è¨Žè«–é€™æ¬¾æ‡‰ç”¨ç¨‹å¼å¦‚何使用地ç†å®šä½è³‡æ–™ï¼Œè³‡æ–™æ˜¯å¦å…±ç”¨å®ƒçš„ä»»ä½•å…¶ä»–ç· ç´„æ–¹å’Œçš„è³‡æ–™ (例如,粗〠細,ZIP 代碼級別,ç‰ç‰ï¼‰ 的精度水準。 地ç†å®šä½è³‡æ–™ä¸€èˆ¬èªç‚ºæ˜¯æ•æ„Ÿï¼Œå› ç‚ºå®ƒèƒ½æç¤ºä½¿ç”¨è€…的下è½ä»¥åŠå¦‚æžœå˜å„²ï¼Œä»–們的旅行的æ·å²ã€‚ å› æ¤ï¼Œé™¤äº†æ‡‰ç”¨ç¨‹å¼çš„éš±ç§æ¬ŠåŽŸå‰‡ï¼Œæ‚¨æ‡‰å¼·çƒˆè€ƒæ…®ä¹‹å‰æ‡‰ç”¨ç¨‹å¼è¨ªå•地ç†å®šä½è³‡æ–™ (如果è¨å‚™ä½œæ¥ç³»çµ±ä¸æœƒé€™æ¨£åšå·²ç¶“) æä¾›åœ¨æ™‚間的通知。 該通知應æä¾›ç›¸åŒçš„資訊上文指出的並ç²å–è©²ä½¿ç”¨è€…çš„è¨±å¯æ¬Š (例如,通éŽç‚º**確定**並**䏿„Ÿè¬**æå‡ºçš„鏿“‡ï¼‰ã€‚ 有關詳細資訊,請åƒé–±éš±ç§æŒ‡å—。 + +這個外掛程å¼å®šç¾©äº†ä¸€å€‹å…¨çƒ `navigator.geolocation` 物件 (為平臺哪裡å¦å‰‡ä¸Ÿå¤±ï¼‰ã€‚ + +儘管物件是在全çƒç¯„åœå…§ï¼Œæä¾›é€™å€‹å¤–掛程å¼çš„功能ä¸å¯ç”¨ç›´åˆ° `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## å®‰è£ + + cordova plugin add cordova-plugin-geolocation + + +## 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± +* iOS +* Tizen +* Windows Phone 7 å’Œ 8 +* Windows 8 + +## 方法 + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## 物件 (唯讀) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +返回è¨å‚™çš„ç•¶å‰ä½ç½®åˆ° `geolocationSuccess` 回檔與 `Position` ç‰©ä»¶ä½œç‚ºåƒæ•¸ã€‚ 如果有錯誤,`geolocationError` 回檔傳éžä¸€å€‹ `PositionError` 物件。 + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### åƒæ•¸ + +* **geolocationSuccess**: 傳éžç•¶å‰ä½ç½®çš„回檔。 + +* **geolocationError**: *(å¯é¸ï¼‰*如果錯誤發生時執行的回檔。 + +* **geolocationOptions**: *(å¯é¸ï¼‰*地ç†å®šä½é¸é …。 + +### 示例 + + // onSuccess Callback + // This method accepts a Position object, which contains the + // current GPS coordinates + // + var onSuccess = function(position) { + alert('Latitude: ' + position.coords.latitude + '\n' + + 'Longitude: ' + position.coords.longitude + '\n' + + 'Altitude: ' + position.coords.altitude + '\n' + + 'Accuracy: ' + position.coords.accuracy + '\n' + + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + + 'Heading: ' + position.coords.heading + '\n' + + 'Speed: ' + position.coords.speed + '\n' + + 'Timestamp: ' + position.timestamp + '\n'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +返回è¨å‚™çš„ç•¶å‰çš„ä½ç½®ï¼Œç•¶æª¢æ¸¬åˆ°æ›´æ”¹ä½ç½®ã€‚ ç•¶è¨å‚™æª¢ç´¢ä¸€å€‹æ–°ä½ç½®æ™‚,則 `geolocationSuccess` 回檔執行與 `Position` ç‰©ä»¶ä½œç‚ºåƒæ•¸ã€‚ 如果有錯誤,則 `geolocationError` 回檔執行åŒä¸€å€‹ `PositionError` ç‰©ä»¶ä½œç‚ºåƒæ•¸ã€‚ + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### åƒæ•¸ + +* **geolocationSuccess**: 傳éžç•¶å‰ä½ç½®çš„回檔。 + +* **geolocationError**: (å¯é¸ï¼‰ 如果錯誤發生時執行的回檔。 + +* **geolocationOptions**: (å¯é¸ï¼‰ 地ç†å®šä½é¸é …。 + +### 返回 + +* **String**: 返回引用的觀看ä½ç½®é–“隔的表 id。 應與一起使用的表 id `navigator.geolocation.clearWatch` åœæ¢äº†è§€çœ‹ä¸ä½ç½®çš„æ›´æ”¹ã€‚ + +### 示例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + + 'Longitude: ' + position.coords.longitude + '<br />' + + '<hr />' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +è‹¥è¦è‡ªè¨‚çš„åœ°ç† `Position` 檢索的å¯é¸åƒæ•¸. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### é¸é … + +* **enableHighAccuracy**: æä¾›æ‡‰ç”¨ç¨‹å¼éœ€è¦æœ€ä½³çš„å¯èƒ½çµæžœçš„æç¤ºã€‚ é è¨æƒ…æ³ä¸‹ï¼Œè©²è¨å‚™å°‡å˜—試檢索 `Position` 使用基於網路的方法。 å°‡æ¤å±¬æ€§è¨ç½®ç‚º `true` 告訴è¦ä½¿ç”¨æ›´ç²¾ç¢ºçš„æ–¹æ³•,如衛星定ä½çš„æ¡†æž¶ã€‚ *(布林值)* + +* **timeout**: 時間 (毫秒) 從調用傳éžï¼Œå…許的最大長度 `navigator.geolocation.getCurrentPosition` 或 `geolocation.watchPosition` 直到相應的 `geolocationSuccess` 回檔執行。 如果 `geolocationSuccess` 䏿œƒåœ¨æ¤æ™‚間內調用回檔 `geolocationError` 傳éžå›žæª” `PositionError.TIMEOUT` 錯誤代碼。 (請注æ„,與一起使用時 `geolocation.watchPosition` 〠`geolocationError` 的時間間隔å¯ä»¥èª¿ç”¨å›žæª”æ¯ `timeout` 毫秒!)*(人數)* + +* **maximumAge**: 接å—其年齡大於指定以毫秒為單ä½çš„æ™‚間沒有緩å˜çš„ä½ç½®ã€‚*(人數)* + +### Android 的怪癖 + +Android 2.x 模擬器ä¸é™¤éž `enableHighAccuracy` é¸é …è¨ç½®ç‚º `true`,å¦å‰‡è¿”回地ç†å®šä½çµæžœ. + +## navigator.geolocation.clearWatch + +åœæ¢è§€å¯Ÿåˆ° `watchID` åƒæ•¸æ‰€å¼•用的è¨å‚™çš„ä½ç½®ã€‚ + + navigator.geolocation.clearWatch(watchID); + + +### åƒæ•¸ + +* **watchID**: çš„ id `watchPosition` 清除的時間間隔。(å—串) + +### 示例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +åŒ…å« `Position` 座標和時間戳記,由地ç†ä½ç½® API 創建。 + +### 屬性 + +* **coords**: 一組的地ç†åº§æ¨™ã€‚*(座標)* + +* **timestamp**: 創建時間戳記為 `coords` 。*(日期)* + +## Coordinates + +`Coordinates` çš„ç‰©ä»¶é™„åŠ åˆ°ä¸€å€‹ `Position` 物件,å¯ç”¨æ–¼åœ¨ç•¶å‰è·ä½çš„請求ä¸çš„回呼函數。 它包å«ä¸€çµ„屬性æè¿°ä½ç½®çš„地ç†åº§æ¨™ã€‚ + +### 屬性 + +* **latitude**: 緯度以å進ä½åº¦ç‚ºå–®ä½ã€‚*(人數)* + +* **longitude**: 經度以å進ä½åº¦ç‚ºå–®ä½ã€‚*(人數)* + +* **altitude**: 高度在米以上橢çƒé«”ä¸çš„ä½ç½®ã€‚*(人數)* + +* **accuracy**: ä¸ç±³çš„緯度和經度座標的精度級別。*(人數)* + +* **altitudeAccuracy**: 在米的海拔高度座標的精度級別。*(人數)* + +* **heading**: 旅行,指定以度為單ä½å…ƒæ•¸ç›®ç›¸å°æ–¼çœŸåŒ—é †æ™‚é‡æ–¹å‘。*(人數)* + +* **speed**: ç•¶å‰åœ°é¢é€Ÿåº¦çš„è¨å‚™ï¼ŒæŒ‡å®šåœ¨ç±³æ¯ç§’。*(人數)* + +### 亞馬éœç« OS 怪癖 + +**altitudeAccuracy**: 䏿”¯æ´çš„ Android è¨å‚™ï¼Œè¿”回 `null`. + +### Android 的怪癖 + +**altitudeAccuracy**: 䏿”¯æ´çš„ Android è¨å‚™ï¼Œè¿”回 `null`. + +## PositionError + +`PositionError` 物件將傳éžçµ¦ `geolocationError` 回呼函數ä¸ï¼Œç•¶å‡ºç¾ navigator.geolocation 錯誤時發生。 + +### 屬性 + +* **code**: 下é¢åˆ—出的é 定義的錯誤代碼之一。 + +* **message**: æè¿°æ‰€é‡åˆ°çš„錯誤的詳細資訊的錯誤訊æ¯ã€‚ + +### å¸¸é‡ + +* `PositionError.PERMISSION_DENIED` + * 返回當使用者ä¸å…è¨±æ‡‰ç”¨ç¨‹å¼æª¢ç´¢çš„ä½ç½®è³‡è¨Šã€‚é€™æ˜¯å–æ±ºæ–¼å¹³è‡ºã€‚ +* `PositionError.POSITION_UNAVAILABLE` + * 返回è¨å‚™æ™‚,ä¸èƒ½æª¢ç´¢çš„ä½ç½®ã€‚一般情æ³ä¸‹ï¼Œé€™æ„味著該è¨å‚™æœªé€£æŽ¥åˆ°ç¶²è·¯æˆ–無法ç²å–衛星的修復。 +* `PositionError.TIMEOUT` + * 返回è¨å‚™æ™‚,無法在指定的時間內檢索ä½ç½® `timeout` ä¸åŒ…å« `geolocationOptions` 。 與一起使用時 `navigator.geolocation.watchPosition` ,æ¤éŒ¯èª¤å¯èƒ½å復傳éžçµ¦ `geolocationError` å›žæª”æ¯ `timeout` 毫秒為單ä½ï¼‰ã€‚ diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/package.json b/StoneIsland/plugins/cordova-plugin-geolocation/package.json new file mode 100644 index 00000000..dee3543b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/package.json @@ -0,0 +1,41 @@ +{ + "name": "cordova-plugin-geolocation", + "version": "1.0.1", + "description": "Cordova Geolocation Plugin", + "cordova": { + "id": "cordova-plugin-geolocation", + "platforms": [ + "android", + "amazon-fireos", + "ios", + "blackberry10", + "ubuntu", + "wp7", + "wp8", + "windows8", + "windows", + "firefoxos" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-geolocation" + }, + "keywords": [ + "cordova", + "geolocation", + "ecosystem:cordova", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ios", + "cordova-blackberry10", + "cordova-ubuntu", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows", + "cordova-firefoxos" + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/plugin.xml b/StoneIsland/plugins/cordova-plugin-geolocation/plugin.xml new file mode 100644 index 00000000..4c0a41d1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/plugin.xml @@ -0,0 +1,248 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" +xmlns:rim="http://www.blackberry.com/ns/widgets" +xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-geolocation" + version="1.0.1"> + + <name>Geolocation</name> + <description>Cordova Geolocation Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,geolocation</keywords> + <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git</repo> + <issue>https://issues.apache.org/jira/browse/CB/component/12320638</issue> + + <!-- android --> + <platform name="android"> + + <config-file target="AndroidManifest.xml" parent="/*"> + <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> + <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> + </config-file> + + </platform> + + <!-- amazon-fireos --> + <platform name="amazon-fireos"> + + <config-file target="AndroidManifest.xml" parent="/*"> + <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> + <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> + </config-file> + + </platform> + + <!-- ios --> + <platform name="ios"> + + <js-module src="www/Coordinates.js" name="Coordinates"> + <clobbers target="Coordinates" /> + </js-module> + + <js-module src="www/PositionError.js" name="PositionError"> + <clobbers target="PositionError" /> + </js-module> + + <js-module src="www/Position.js" name="Position"> + <clobbers target="Position" /> + </js-module> + + <js-module src="www/geolocation.js" name="geolocation"> + <clobbers target="navigator.geolocation" /> + </js-module> + + <config-file target="config.xml" parent="/*"> + <feature name="Geolocation"> + <param name="ios-package" value="CDVLocation"/> + </feature> + </config-file> + <header-file src="src/ios/CDVLocation.h" /> + <source-file src="src/ios/CDVLocation.m" /> + <framework src="CoreLocation.framework" /> + + <config-file target="*-Info.plist" parent="NSLocationWhenInUseUsageDescription"> + <string></string> + </config-file> + + </platform> + + <!-- blackberry10 --> + <platform name="blackberry10"> + + <js-module src="www/blackberry10/GeolocationProxy.js" name="GeolocationProxy"> + <runs /> + </js-module> + + <js-module src="www/Coordinates.js" name="Coordinates"> + <clobbers target="Coordinates" /> + </js-module> + + <js-module src="www/PositionError.js" name="PositionError"> + <clobbers target="PositionError" /> + </js-module> + + <js-module src="www/Position.js" name="Position"> + <clobbers target="Position" /> + </js-module> + + <js-module src="www/geolocation.js" name="geolocation"> + <clobbers target="navigator.geolocation" /> + </js-module> + + <config-file target="www/config.xml" parent="/widget"> + <feature name="Geolocation" value="Geolocation"/> + </config-file> + + <config-file target="www/config.xml" parent="/widget/rim:permissions"> + <rim:permit>read_geolocation</rim:permit> + </config-file> + + </platform> + + <!-- ubuntu --> + <platform name="ubuntu"> + <js-module src="www/Coordinates.js" name="Coordinates"> + <clobbers target="Coordinates" /> + </js-module> + + <js-module src="www/PositionError.js" name="PositionError"> + <clobbers target="PositionError" /> + </js-module> + + <js-module src="www/Position.js" name="Position"> + <clobbers target="Position" /> + </js-module> + + <js-module src="www/geolocation.js" name="geolocation"> + <clobbers target="navigator.geolocation" /> + </js-module> + + <source-file src="src/ubuntu/geolocation.cpp" /> + <header-file src="src/ubuntu/geolocation.h" /> + <config-file target="config.xml" parent="/*"> + <feature name="Geolocation"> + <param policy_group="location" policy_version="1" /> + </feature> + </config-file> + </platform> + + <!-- wp7 --> + <platform name="wp7"> + + <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> + <Capability Name="ID_CAP_LOCATION" /> + </config-file> + + <source-file src="src/wp/Geolocation.cs" /> + </platform> + + <!-- wp8 --> + <platform name="wp8"> + + <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> + <Capability Name="ID_CAP_LOCATION" /> + </config-file> + + <source-file src="src/wp/Geolocation.cs" /> + </platform> + + <!-- windows8 --> + <platform name="windows8"> + <config-file target="package.appxmanifest" parent="/Package/Capabilities"> + <DeviceCapability Name="location" /> + </config-file> + + <js-module src="src/windows/GeolocationProxy.js" name="GeolocationProxy"> + <runs /> + </js-module> + + <js-module src="www/Coordinates.js" name="Coordinates"> + <clobbers target="Coordinates" /> + </js-module> + + <js-module src="www/PositionError.js" name="PositionError"> + <clobbers target="PositionError" /> + </js-module> + + <js-module src="www/Position.js" name="Position"> + <clobbers target="Position" /> + </js-module> + + <js-module src="www/geolocation.js" name="geolocation"> + <clobbers target="navigator.geolocation" /> + </js-module> + </platform> + + <!-- windows universal apps (Windows 8.1, Windows Phone 8.1, Windows 8.0) --> + <platform name="windows"> + <config-file target="package.appxmanifest" parent="/Package/Capabilities"> + <DeviceCapability Name="location" /> + </config-file> + + <js-module src="src/windows/GeolocationProxy.js" name="GeolocationProxy"> + <runs /> + </js-module> + + <js-module src="www/Coordinates.js" name="Coordinates"> + <clobbers target="Coordinates" /> + </js-module> + + <js-module src="www/PositionError.js" name="PositionError"> + <clobbers target="PositionError" /> + </js-module> + + <js-module src="www/Position.js" name="Position"> + <clobbers target="Position" /> + </js-module> + + <js-module src="www/geolocation.js" name="geolocation"> + <clobbers target="navigator.geolocation" /> + </js-module> + </platform> + + <!-- firefoxos --> + <platform name="firefoxos"> + <config-file target="config.xml" parent="/*"> + <permission name="geolocation" description="Required for accessing user location." /> + </config-file> + + <js-module src="src/firefoxos/GeolocationProxy.js" name="GeolocationProxy"> + <runs /> + </js-module> + + <js-module src="www/Coordinates.js" name="Coordinates"> + <clobbers target="Coordinates" /> + </js-module> + + <js-module src="www/PositionError.js" name="PositionError"> + <clobbers target="PositionError" /> + </js-module> + + <js-module src="www/Position.js" name="Position"> + <clobbers target="Position" /> + </js-module> + + <js-module src="www/geolocation.js" name="geolocation"> + <clobbers target="navigator.geolocation" /> + </js-module> + </platform> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/firefoxos/GeolocationProxy.js b/StoneIsland/plugins/cordova-plugin-geolocation/src/firefoxos/GeolocationProxy.js new file mode 100644 index 00000000..e4b40529 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/firefoxos/GeolocationProxy.js @@ -0,0 +1,67 @@ +/* + * + * 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. + * +*/ + +// latest geolocation spec can be found here: http://www.w3.org/TR/geolocation-API/ + +var idsMap = {}; + +module.exports = { + getLocation: function(success, error, args) { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + function successCallback(position) { + // Cordova is creating Position object using just coords + success(position.coords); + } + geo.getCurrentPosition(successCallback, error, { + enableHighAccuracy: args[0], + maximumAge: args[1] + }); + }, + + addWatch: function(success, error, args) { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + var id = args[0]; + function successCallback(position) { + success(position.coords); + } + var nativeId = geo.watchPosition(successCallback, error, { + enableHighAccuracy: args[1] + }); + + idsMap[id] = nativeId; + }, + + clearWatch: function(success, error, args) { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + var id = args[0]; + + if(id in idsMap) { + geo.clearWatch(idsMap[id]); + delete idsMap[id]; + } + + if(success) { + success(); + } + } +}; + +require("cordova/exec/proxy").add("Geolocation", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.h b/StoneIsland/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.h new file mode 100644 index 00000000..cce2738f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.h @@ -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 <UIKit/UIKit.h> +#import <CoreLocation/CoreLocation.h> +#import <Cordova/CDVPlugin.h> + +enum CDVLocationStatus { + PERMISSIONDENIED = 1, + POSITIONUNAVAILABLE, + TIMEOUT +}; +typedef NSUInteger CDVLocationStatus; + +// simple object to keep track of location information +@interface CDVLocationData : NSObject { + CDVLocationStatus locationStatus; + NSMutableArray* locationCallbacks; + NSMutableDictionary* watchCallbacks; + CLLocation* locationInfo; +} + +@property (nonatomic, assign) CDVLocationStatus locationStatus; +@property (nonatomic, strong) CLLocation* locationInfo; +@property (nonatomic, strong) NSMutableArray* locationCallbacks; +@property (nonatomic, strong) NSMutableDictionary* watchCallbacks; + +@end + +@interface CDVLocation : CDVPlugin <CLLocationManagerDelegate>{ + @private BOOL __locationStarted; + @private BOOL __highAccuracyEnabled; + CDVLocationData* locationData; +} + +@property (nonatomic, strong) CLLocationManager* locationManager; +@property (nonatomic, strong) CDVLocationData* locationData; + +- (void)getLocation:(CDVInvokedUrlCommand*)command; +- (void)addWatch:(CDVInvokedUrlCommand*)command; +- (void)clearWatch:(CDVInvokedUrlCommand*)command; +- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback; +- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message; +- (void)startLocation:(BOOL)enableHighAccuracy; + +- (void)locationManager:(CLLocationManager*)manager + didUpdateToLocation:(CLLocation*)newLocation + fromLocation:(CLLocation*)oldLocation; + +- (void)locationManager:(CLLocationManager*)manager + didFailWithError:(NSError*)error; + +- (BOOL)isLocationServicesEnabled; +@end diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.m b/StoneIsland/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.m new file mode 100644 index 00000000..8b543c8e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.m @@ -0,0 +1,366 @@ +/* + 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 "CDVLocation.h" + +#pragma mark Constants + +#define kPGLocationErrorDomain @"kPGLocationErrorDomain" +#define kPGLocationDesiredAccuracyKey @"desiredAccuracy" +#define kPGLocationForcePromptKey @"forcePrompt" +#define kPGLocationDistanceFilterKey @"distanceFilter" +#define kPGLocationFrequencyKey @"frequency" + +#pragma mark - +#pragma mark Categories + +@implementation CDVLocationData + +@synthesize locationStatus, locationInfo, locationCallbacks, watchCallbacks; +- (CDVLocationData*)init +{ + self = (CDVLocationData*)[super init]; + if (self) { + self.locationInfo = nil; + self.locationCallbacks = nil; + self.watchCallbacks = nil; + } + return self; +} + +@end + +#pragma mark - +#pragma mark CDVLocation + +@implementation CDVLocation + +@synthesize locationManager, locationData; + +- (void)pluginInitialize +{ + self.locationManager = [[CLLocationManager alloc] init]; + self.locationManager.delegate = self; // Tells the location manager to send updates to this object + __locationStarted = NO; + __highAccuracyEnabled = NO; + self.locationData = nil; +} + +- (BOOL)isAuthorized +{ + BOOL authorizationStatusClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+ + + if (authorizationStatusClassPropertyAvailable) { + NSUInteger authStatus = [CLLocationManager authorizationStatus]; +#ifdef __IPHONE_8_0 + if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { //iOS 8.0+ + return (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) || (authStatus == kCLAuthorizationStatusAuthorizedAlways) || (authStatus == kCLAuthorizationStatusNotDetermined); + } +#endif + return (authStatus == kCLAuthorizationStatusAuthorized) || (authStatus == kCLAuthorizationStatusNotDetermined); + } + + // by default, assume YES (for iOS < 4.2) + return YES; +} + +- (BOOL)isLocationServicesEnabled +{ + BOOL locationServicesEnabledInstancePropertyAvailable = [self.locationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 3.x + BOOL locationServicesEnabledClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 4.x + + if (locationServicesEnabledClassPropertyAvailable) { // iOS 4.x + return [CLLocationManager locationServicesEnabled]; + } else if (locationServicesEnabledInstancePropertyAvailable) { // iOS 2.x, iOS 3.x + return [(id)self.locationManager locationServicesEnabled]; + } else { + return NO; + } +} + +- (void)startLocation:(BOOL)enableHighAccuracy +{ + if (![self isLocationServicesEnabled]) { + [self returnLocationError:PERMISSIONDENIED withMessage:@"Location services are not enabled."]; + return; + } + if (![self isAuthorized]) { + NSString* message = nil; + BOOL authStatusAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+ + if (authStatusAvailable) { + NSUInteger code = [CLLocationManager authorizationStatus]; + if (code == kCLAuthorizationStatusNotDetermined) { + // could return POSITION_UNAVAILABLE but need to coordinate with other platforms + message = @"User undecided on application's use of location services."; + } else if (code == kCLAuthorizationStatusRestricted) { + message = @"Application's use of location services is restricted."; + } + } + // PERMISSIONDENIED is only PositionError that makes sense when authorization denied + [self returnLocationError:PERMISSIONDENIED withMessage:message]; + + return; + } + +#ifdef __IPHONE_8_0 + NSUInteger code = [CLLocationManager authorizationStatus]; + if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) { //iOS8+ + __highAccuracyEnabled = enableHighAccuracy; + if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){ + [self.locationManager requestAlwaysAuthorization]; + } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) { + [self.locationManager requestWhenInUseAuthorization]; + } else { + NSLog(@"[Warning] No NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key is defined in the Info.plist file."); + } + return; + } +#endif + + // Tell the location manager to start notifying us of location updates. We + // first stop, and then start the updating to ensure we get at least one + // update, even if our location did not change. + [self.locationManager stopUpdatingLocation]; + [self.locationManager startUpdatingLocation]; + __locationStarted = YES; + if (enableHighAccuracy) { + __highAccuracyEnabled = YES; + // Set distance filter to 5 for a high accuracy. Setting it to "kCLDistanceFilterNone" could provide a + // higher accuracy, but it's also just spamming the callback with useless reports which drain the battery. + self.locationManager.distanceFilter = 5; + // Set desired accuracy to Best. + self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; + } else { + __highAccuracyEnabled = NO; + // TODO: Set distance filter to 10 meters? and desired accuracy to nearest ten meters? arbitrary. + self.locationManager.distanceFilter = 10; + self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; + } +} + +- (void)_stopLocation +{ + if (__locationStarted) { + if (![self isLocationServicesEnabled]) { + return; + } + + [self.locationManager stopUpdatingLocation]; + __locationStarted = NO; + __highAccuracyEnabled = NO; + } +} + +- (void)locationManager:(CLLocationManager*)manager + didUpdateToLocation:(CLLocation*)newLocation + fromLocation:(CLLocation*)oldLocation +{ + CDVLocationData* cData = self.locationData; + + cData.locationInfo = newLocation; + if (self.locationData.locationCallbacks.count > 0) { + for (NSString* callbackId in self.locationData.locationCallbacks) { + [self returnLocationInfo:callbackId andKeepCallback:NO]; + } + + [self.locationData.locationCallbacks removeAllObjects]; + } + if (self.locationData.watchCallbacks.count > 0) { + for (NSString* timerId in self.locationData.watchCallbacks) { + [self returnLocationInfo:[self.locationData.watchCallbacks objectForKey:timerId] andKeepCallback:YES]; + } + } else { + // No callbacks waiting on us anymore, turn off listening. + [self _stopLocation]; + } +} + +- (void)getLocation:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + BOOL enableHighAccuracy = [[command argumentAtIndex:0] boolValue]; + + if ([self isLocationServicesEnabled] == NO) { + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"]; + [posError setObject:@"Location services are disabled." forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } else { + if (!self.locationData) { + self.locationData = [[CDVLocationData alloc] init]; + } + CDVLocationData* lData = self.locationData; + if (!lData.locationCallbacks) { + lData.locationCallbacks = [NSMutableArray arrayWithCapacity:1]; + } + + if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) { + // add the callbackId into the array so we can call back when get data + if (callbackId != nil) { + [lData.locationCallbacks addObject:callbackId]; + } + // Tell the location manager to start notifying us of heading updates + [self startLocation:enableHighAccuracy]; + } else { + [self returnLocationInfo:callbackId andKeepCallback:NO]; + } + } +} + +- (void)addWatch:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* timerId = [command argumentAtIndex:0]; + BOOL enableHighAccuracy = [[command argumentAtIndex:1] boolValue]; + + if (!self.locationData) { + self.locationData = [[CDVLocationData alloc] init]; + } + CDVLocationData* lData = self.locationData; + + if (!lData.watchCallbacks) { + lData.watchCallbacks = [NSMutableDictionary dictionaryWithCapacity:1]; + } + + // add the callbackId into the dictionary so we can call back whenever get data + [lData.watchCallbacks setObject:callbackId forKey:timerId]; + + if ([self isLocationServicesEnabled] == NO) { + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"]; + [posError setObject:@"Location services are disabled." forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } else { + if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) { + // Tell the location manager to start notifying us of location updates + [self startLocation:enableHighAccuracy]; + } + } +} + +- (void)clearWatch:(CDVInvokedUrlCommand*)command +{ + NSString* timerId = [command argumentAtIndex:0]; + + if (self.locationData && self.locationData.watchCallbacks && [self.locationData.watchCallbacks objectForKey:timerId]) { + [self.locationData.watchCallbacks removeObjectForKey:timerId]; + if([self.locationData.watchCallbacks count] == 0) { + [self _stopLocation]; + } + } +} + +- (void)stopLocation:(CDVInvokedUrlCommand*)command +{ + [self _stopLocation]; +} + +- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback +{ + CDVPluginResult* result = nil; + CDVLocationData* lData = self.locationData; + + if (lData && !lData.locationInfo) { + // return error + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:POSITIONUNAVAILABLE]; + } else if (lData && lData.locationInfo) { + CLLocation* lInfo = lData.locationInfo; + NSMutableDictionary* returnInfo = [NSMutableDictionary dictionaryWithCapacity:8]; + NSNumber* timestamp = [NSNumber numberWithDouble:([lInfo.timestamp timeIntervalSince1970] * 1000)]; + [returnInfo setObject:timestamp forKey:@"timestamp"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.speed] forKey:@"velocity"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.verticalAccuracy] forKey:@"altitudeAccuracy"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.horizontalAccuracy] forKey:@"accuracy"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.course] forKey:@"heading"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.altitude] forKey:@"altitude"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.latitude] forKey:@"latitude"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.longitude] forKey:@"longitude"]; + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:returnInfo]; + [result setKeepCallbackAsBool:keepCallback]; + } + if (result) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } +} + +- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message +{ + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + + [posError setObject:[NSNumber numberWithUnsignedInteger:errorCode] forKey:@"code"]; + [posError setObject:message ? message:@"" forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + + for (NSString* callbackId in self.locationData.locationCallbacks) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } + + [self.locationData.locationCallbacks removeAllObjects]; + + for (NSString* callbackId in self.locationData.watchCallbacks) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } +} + +- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error +{ + NSLog(@"locationManager::didFailWithError %@", [error localizedFailureReason]); + + CDVLocationData* lData = self.locationData; + if (lData && __locationStarted) { + // TODO: probably have to once over the various error codes and return one of: + // PositionError.PERMISSION_DENIED = 1; + // PositionError.POSITION_UNAVAILABLE = 2; + // PositionError.TIMEOUT = 3; + NSUInteger positionError = POSITIONUNAVAILABLE; + if (error.code == kCLErrorDenied) { + positionError = PERMISSIONDENIED; + } + [self returnLocationError:positionError withMessage:[error localizedDescription]]; + } + + if (error.code != kCLErrorLocationUnknown) { + [self.locationManager stopUpdatingLocation]; + __locationStarted = NO; + } +} + +//iOS8+ +-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status +{ + if(!__locationStarted){ + [self startLocation:__highAccuracyEnabled]; + } +} + +- (void)dealloc +{ + self.locationManager.delegate = nil; +} + +- (void)onReset +{ + [self _stopLocation]; + [self.locationManager stopUpdatingHeading]; +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.cpp b/StoneIsland/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.cpp new file mode 100644 index 00000000..c820cfef --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.cpp @@ -0,0 +1,119 @@ +/* + * + * Copyright 2013 Canonical Ltd. + * + * Licensed 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 <QUuid> + +#include "geolocation.h" + +Geolocation::Geolocation(Cordova *cordova): CPlugin(cordova), + _geoPositionInfoSource(QGeoPositionInfoSource::createDefaultSource(this)) { + if (_geoPositionInfoSource.data() != 0) { + QObject::connect(_geoPositionInfoSource.data(), SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); + QObject::connect(_geoPositionInfoSource.data(), SIGNAL(updateTimeout()), this, SLOT(updateTimeout())); + } +} + +void Geolocation::addWatch(int scId, int ecId, const QString &id, bool enableHighAccuracy) { + Q_UNUSED(enableHighAccuracy); + + assert(_id2sc.find(id) == _id2sc.end()); + + if (!_geoPositionInfoSource.data()) { + QVariantMap err; + err.insert("code", POSITION_UNAVAILABLE); + err.insert("message", "unavailable"); + + this->cb(ecId, err); + return; + } + + _id2sc[id] = scId; + _id2ec[id] = ecId; +} + +void Geolocation::clearWatch(int scId, int ecId, const QString &id) { + _id2sc.remove(id); + _id2ec.remove(id); +} + +void Geolocation::getLocation(int scId, int ecId, bool enableHighAccuracy, qint64 maximumAge) { + Q_UNUSED(maximumAge); + Q_UNUSED(enableHighAccuracy); + + if (!_geoPositionInfoSource.data()) { + QVariantMap err; + err.insert("code", POSITION_UNAVAILABLE); + err.insert("message", "unavailable"); + + this->cb(ecId, err); + return; + } + + _geoPositionInfoSource->requestUpdate(); + + QString id = QString("_INTERNAL_") + QUuid::createUuid().toString(); + + _id2sc[id] = scId; + _id2ec[id] = ecId; + _singleUpdate.insert(id); +} + +void Geolocation::positionUpdated(const QGeoPositionInfo &update) { + QGeoCoordinate coordinate = update.coordinate(); + + QVariantMap p; + + p.insert("latitude", coordinate.latitude()); + p.insert("longitude", coordinate.longitude()); + p.insert("altitude", coordinate.altitude()); + + if (update.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) + p.insert("accuracy", update.attribute(QGeoPositionInfo::VerticalAccuracy)); + if (update.hasAttribute(QGeoPositionInfo::Direction)) + p.insert("heading", update.attribute(QGeoPositionInfo::Direction)); + if (update.hasAttribute(QGeoPositionInfo::GroundSpeed)) + p.insert("velocity", update.attribute(QGeoPositionInfo::GroundSpeed)); + if (update.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) + p.insert("altitudeAccuracy", update.attribute(QGeoPositionInfo::HorizontalAccuracy)); + p.insert("timestamp", update.timestamp().toMSecsSinceEpoch()); + + for (const QString &id: _id2sc.keys()) { + int scId = _id2sc[id]; + this->cb(scId, p); + if (_singleUpdate.contains(id)) { + _singleUpdate.remove(id); + _id2sc.remove(id); + _id2ec.remove(id); + } + } +} + +void Geolocation::updateTimeout() { + QVariantMap err; + err.insert("code", TIMEOUT); + err.insert("message", "timeout"); + + for (int ecId: _id2ec) { + this->cb(ecId, err); + } + + _id2ec.clear(); + _id2sc.clear(); + _singleUpdate.clear(); +} diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.h b/StoneIsland/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.h new file mode 100644 index 00000000..7345bec9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.h @@ -0,0 +1,69 @@ +/* + * + * Copyright 2013 Canonical Ltd. + * + * Licensed 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 GEOLOCATION_H_SVO2013 +#define GEOLOCATION_H_SVO2013 + +#include <QGeoPositionInfoSource> +#include <QGeoPositionInfo> +#include <QtCore> +#include <cassert> + +#include <cplugin.h> + +class Geolocation: public CPlugin { + Q_OBJECT +public: + explicit Geolocation(Cordova *cordova); + + virtual const QString fullName() override { + return Geolocation::fullID(); + } + + virtual const QString shortName() override { + return "Geolocation"; + } + + static const QString fullID() { + return "Geolocation"; + } + +public slots: + void getLocation(int scId, int ecId, bool enableHighAccuracy, qint64 maximumAge); + void addWatch(int scId, int ecId, const QString &id, bool enableHighAccuracy); + void clearWatch(int scId, int ecId, const QString &id); + +protected slots: + void positionUpdated(const QGeoPositionInfo &update); + void updateTimeout(); + +private: + QMap<QString, int> _id2sc; + QMap<QString, int> _id2ec; + QSet<QString> _singleUpdate; + QSharedPointer<QGeoPositionInfoSource> _geoPositionInfoSource; + + enum PositionError { + PERMISSION_DENIED = 1, + POSITION_UNAVAILABLE = 2, + TIMEOUT = 3 + }; +}; + +#endif diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/windows/GeolocationProxy.js b/StoneIsland/plugins/cordova-plugin-geolocation/src/windows/GeolocationProxy.js new file mode 100644 index 00000000..9cab6a4d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/windows/GeolocationProxy.js @@ -0,0 +1,174 @@ +/* + * Copyright 2013 Research In Motion Limited. + * + * Licensed 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 PositionError = require('./PositionError'), + ids = {}, + loc; + +function ensureLocator() { + if (loc == null) + loc = new Windows.Devices.Geolocation.Geolocator(); + + return loc; +} + +function createErrorCode() { + switch (loc.locationStatus) { + case Windows.Devices.Geolocation.PositionStatus.initializing: + // This status indicates that a location device is still initializing + case Windows.Devices.Geolocation.PositionStatus.noData: + // No location data is currently available + case Windows.Devices.Geolocation.PositionStatus.notInitialized: + // This status indicates that the app has not yet requested + // location data by calling GetGeolocationAsync() or + // registering an event handler for the positionChanged event. + case Windows.Devices.Geolocation.PositionStatus.notAvailable: + // Location is not available on this version of Windows + return PositionError.POSITION_UNAVAILABLE; + + case Windows.Devices.Geolocation.PositionStatus.disabled: + // The app doesn't have permission to access location, + // either because location has been turned off. + return PositionError.PERMISSION_DENIED; + + default: + break; + } +} +function createResult(pos) { + var res = { + accuracy: pos.coordinate.accuracy, + heading: pos.coordinate.heading, + velocity: pos.coordinate.speed, + altitudeAccuracy: pos.coordinate.altitudeAccuracy, + timestamp: pos.coordinate.timestamp + } + + if (pos.coordinate.point) { + res.latitude = pos.coordinate.point.position.latitude; + res.longitude = pos.coordinate.point.position.longitude; + res.altitude = pos.coordinate.point.position.altitude; + } else { // compatibility with old windows8.0 api + res.latitude = pos.coordinate.latitude; + res.longitude = pos.coordinate.longitude; + res.altitude = pos.coordinate.altitude; + } + + return res; +} + +module.exports = { + getLocation: function (success, fail, args, env) { + ensureLocator(); + if (loc != null) + { + var highAccuracy = args[0], + maxAge = args[1]; + + loc.desiredAccuracy = highAccuracy ? + Windows.Devices.Geolocation.PositionAccuracy.high : + Windows.Devices.Geolocation.PositionAccuracy.default; + + loc.reportInterval = maxAge ? maxAge : 0; + + loc.getGeopositionAsync().then( + function (pos) { + success(createResult(pos)); + }, + function (err) { + fail({ + code: createErrorCode(), + message: err.message + }); + } + ); + } + else + { + fail({ + code: PositionError.POSITION_UNAVAILABLE, + message: "You do not have the required location services present on your system." + }); + } + }, + + addWatch: function (success, fail, args, env) { + ensureLocator(); + var clientId = args[0], + highAccuracy = args[1], + + onPositionChanged = function (e) { + success(createResult(e.position), {keepCallback: true}); + }, + + onStatusChanged = function (e) { + switch (e.status) { + case Windows.Devices.Geolocation.PositionStatus.noData: + case Windows.Devices.Geolocation.PositionStatus.notAvailable: + fail({ + code: PositionError.POSITION_UNAVAILABLE, + message: "Data from location services is currently unavailable or you do not have the required location services present on your system." + }); + break; + + case Windows.Devices.Geolocation.PositionStatus.disabled: + fail({ + code: PositionError.PERMISSION_DENIED, + message: "Your location is currently turned off." + }); + break; + + case Windows.Devices.Geolocation.PositionStatus.initializing: + case Windows.Devices.Geolocation.PositionStatus.ready: + default: + break; + } + }; + + loc.desiredAccuracy = highAccuracy ? + Windows.Devices.Geolocation.PositionAccuracy.high : + Windows.Devices.Geolocation.PositionAccuracy.default; + + if (cordova.platformId == 'windows' && WinJS.Utilities.isPhone) { + // on Windows Phone 8.1 'positionchanged' event fails with error below if movementThreshold is not set + // JavaScript runtime error: Operation aborted + // You must set the MovementThreshold property or the ReportInterval property before adding event handlers. + // WinRT information: You must set the MovementThreshold property or the ReportInterval property before adding event handlers + loc.movementThreshold = loc.movementThreshold || 1; // 1 meter + } + + loc.addEventListener("positionchanged", onPositionChanged); + loc.addEventListener("statuschanged", onStatusChanged); + + ids[clientId] = { pos: onPositionChanged, status: onStatusChanged }; + }, + + clearWatch: function (success, fail, args, env) { + var clientId = args[0], + callbacks = ids[clientId]; + + if (callbacks) { + loc.removeEventListener("positionchanged", callbacks.pos); + loc.removeEventListener("statuschanged", callbacks.status); + + delete ids[clientId]; + } + + success && success(); + } +}; + +require("cordova/exec/proxy").add("Geolocation", module.exports);
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/src/wp/GeoLocation.cs b/StoneIsland/plugins/cordova-plugin-geolocation/src/wp/GeoLocation.cs new file mode 100644 index 00000000..42af72de --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/src/wp/GeoLocation.cs @@ -0,0 +1,34 @@ +/* + Licensed 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. +*/ + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Threading; +using System.Device.Location; + +namespace WPCordovaClassLib.Cordova.Commands +{ + /// <summary> + /// This is a command stub, the browser provides the correct implementation. We use this to trigger the static analyzer that we require this permission + /// </summary> + public class Geolocation + { + /* Unreachable code, by design -jm */ + private void triggerGeoInclusion() + { + new GeoCoordinateWatcher(); + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/tests/plugin.xml b/StoneIsland/plugins/cordova-plugin-geolocation/tests/plugin.xml new file mode 100644 index 00000000..edeb62e1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/tests/plugin.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + xmlns:rim="http://www.blackberry.com/ns/widgets" + xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-geolocation-tests" + version="1.0.1"> + <name>Cordova Geolocation Plugin Tests</name> + <license>Apache 2.0</license> + + <js-module src="tests.js" name="tests"> + </js-module> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/tests/tests.js b/StoneIsland/plugins/cordova-plugin-geolocation/tests/tests.js new file mode 100644 index 00000000..e07caf88 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/tests/tests.js @@ -0,0 +1,425 @@ +/* + * + * 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.defineAutoTests = function () { + var fail = function (done, context, message) { + // prevents done() to be called several times + if (context) { + if (context.done) return; + context.done = true; + } + + if (message) { + expect(false).toBe(true, message); + } else { + expect(false).toBe(true); + } + + // watchPosition could call its callback sync (before returning the value) + // so we invoke done async to make sure we know watcher id to .clear in afterEach + setTimeout(function () { + done(); + }); + }, + succeed = function (done, context) { + // prevents done() to be called several times + if (context) { + if (context.done) return; + context.done = true; + } + + expect(true).toBe(true); + + // watchPosition could call its callback sync (before returning the value) + // so we invoke done async to make sure we know watcher id to .clear in afterEach + setTimeout(function () { + done(); + }); + }, + isWindowsStore = (cordova.platformId == "windows8") || (cordova.platformId == "windows" && !WinJS.Utilities.isPhone), + isAndroid = cordova.platformId == "android"; + + describe('Geolocation (navigator.geolocation)', function () { + + it("geolocation.spec.1 should exist", function () { + expect(navigator.geolocation).toBeDefined(); + }); + + it("geolocation.spec.2 should contain a getCurrentPosition function", function () { + expect(typeof navigator.geolocation.getCurrentPosition).toBeDefined(); + expect(typeof navigator.geolocation.getCurrentPosition == 'function').toBe(true); + }); + + it("geolocation.spec.3 should contain a watchPosition function", function () { + expect(typeof navigator.geolocation.watchPosition).toBeDefined(); + expect(typeof navigator.geolocation.watchPosition == 'function').toBe(true); + }); + + it("geolocation.spec.4 should contain a clearWatch function", function () { + expect(typeof navigator.geolocation.clearWatch).toBeDefined(); + expect(typeof navigator.geolocation.clearWatch == 'function').toBe(true); + }); + + }); + + describe('getCurrentPosition method', function () { + + describe('error callback', function () { + + it("geolocation.spec.5 should be called if we set timeout to 0 and maximumAge to a very small number", function (done) { + // On Windows, this test prompts user for permission to use geolocation and interrupts autotests running. + // On Android geolocation Api is not available on emulator so we pended tests until we found the way to detect + // whether we run on emulator or real device from JavaScript. You can still run the tests on Android manually. + if (isWindowsStore || isAndroid) { + pending(); + } + + navigator.geolocation.getCurrentPosition( + fail.bind(null, done), + succeed.bind(null, done), + { + maximumAge: 0, + timeout: 0 + }); + }); + + }); + + describe('success callback', function () { + + it("geolocation.spec.6 should be called with a Position object", function (done) { + // On Windows, this test prompts user for permission to use geolocation and interrupts autotests running. + // On Android geolocation Api is not available on emulator so we pended tests until we found the way to detect + // whether we run on emulator or real device from JavaScript. You can still run the tests on Android manually. + if (isWindowsStore || isAndroid) { + pending(); + } + + navigator.geolocation.getCurrentPosition(function (p) { + expect(p.coords).toBeDefined(); + expect(p.timestamp).toBeDefined(); + done(); + }, + fail.bind(null, done), + { + maximumAge: (5 * 60 * 1000) // 5 minutes maximum age of cached position + }); + }, 25000); // first geolocation call can take several seconds on some devices + }); + + }); + + describe('watchPosition method', function () { + + beforeEach(function(done) { + // This timeout is set to lessen the load on platform's geolocation services + // which were causing occasional test failures + setTimeout(function() { + done(); + }, 100); + }); + + describe('error callback', function () { + + var errorWatch = null; + afterEach(function () { + navigator.geolocation.clearWatch(errorWatch); + }); + + it("geolocation.spec.7 should be called if we set timeout to 0 and maximumAge to a very small number", function (done) { + // On Windows, this test prompts user for permission to use geolocation and interrupts autotests running. + // On Android geolocation Api is not available on emulator so we pended tests until we found the way to detect + // whether we run on emulator or real device from JavaScript. You can still run the tests on Android manually. + if (isWindowsStore || isAndroid) { + pending(); + } + + var context = this; + errorWatch = navigator.geolocation.watchPosition( + fail.bind(null, done, context, 'Unexpected win'), + succeed.bind(null, done, context), + { + maximumAge: 0, + timeout: 0 + }); + }); + + }); + + describe('success callback', function () { + + var successWatch = null; + afterEach(function () { + navigator.geolocation.clearWatch(successWatch); + }); + + it("geolocation.spec.8 should be called with a Position object", function (done) { + // On Windows, this test prompts user for permission to use geolocation and interrupts autotests running. + // On Android geolocation Api is not available on emulator so we pended tests until we found the way to detect + // whether we run on emulator or real device from JavaScript. You can still run the tests on Android manually. + if (isWindowsStore || isAndroid) { + pending(); + } + + var context = this; + successWatch = navigator.geolocation.watchPosition( + function (p) { + // prevents done() to be called several times + if (context.done) return; + context.done = true; + + expect(p.coords).toBeDefined(); + expect(p.timestamp).toBeDefined(); + // callback could be called sync so we invoke done async to make sure we know watcher id to .clear in afterEach + setTimeout(function () { + done(); + }); + }, + fail.bind(null, done, context, 'Unexpected fail callback'), + { + maximumAge: (5 * 60 * 1000) // 5 minutes maximum age of cached position + }); + }); + + }); + + }); + +}; + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +exports.defineManualTests = function (contentEl, createActionButton) { + var newGeolocation = navigator.geolocation; + var origGeolocation = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + if (!origGeolocation) { + origGeolocation = newGeolocation; + newGeolocation = null; + } + + var watchLocationId = null; + + /** + * Start watching location + */ + var watchLocation = function (usePlugin) { + console.log("watchLocation()"); + var geo = usePlugin ? newGeolocation : origGeolocation; + if (!geo) { + alert('geolocation object is missing. usePlugin = ' + usePlugin); + return; + } + + // Success callback + var success = function (p) { + setLocationDetails(p); + }; + + // Fail callback + var fail = function (e) { + console.log("watchLocation fail callback with error code " + e); + stopLocation(geo); + }; + + // Get location + watchLocationId = geo.watchPosition(success, fail, { enableHighAccuracy: true }); + setLocationStatus("Running"); + }; + + /** + * Stop watching the location + */ + var stopLocation = function (usePlugin) { + console.log("stopLocation()"); + var geo = usePlugin ? newGeolocation : origGeolocation; + if (!geo) { + alert('geolocation object is missing. usePlugin = ' + usePlugin); + return; + } + setLocationStatus("Stopped"); + if (watchLocationId) { + geo.clearWatch(watchLocationId); + watchLocationId = null; + } + }; + + /** + * Get current location + */ + var getLocation = function (usePlugin, opts) { + console.log("getLocation()"); + var geo = usePlugin ? newGeolocation : origGeolocation; + if (!geo) { + alert('geolocation object is missing. usePlugin = ' + usePlugin); + return; + } + + // Stop location if running + stopLocation(geo); + + // Success callback + var success = function (p) { + setLocationDetails(p); + setLocationStatus("Done"); + }; + + // Fail callback + var fail = function (e) { + console.log("getLocation fail callback with error code " + e.code); + setLocationStatus("Error: " + e.code); + }; + + setLocationStatus("Retrieving location..."); + + // Get location + geo.getCurrentPosition(success, fail, opts || { enableHighAccuracy: true }); //, {timeout: 10000}); + + }; + + /** + * Set location status + */ + var setLocationStatus = function (status) { + document.getElementById('location_status').innerHTML = status; + }; + var setLocationDetails = function (p) { + var date = (new Date(p.timestamp)); + document.getElementById('latitude').innerHTML = p.coords.latitude; + document.getElementById('longitude').innerHTML = p.coords.longitude; + document.getElementById('altitude').innerHTML = p.coords.altitude; + document.getElementById('accuracy').innerHTML = p.coords.accuracy; + document.getElementById('heading').innerHTML = p.coords.heading; + document.getElementById('speed').innerHTML = p.coords.speed; + document.getElementById('altitude_accuracy').innerHTML = p.coords.altitudeAccuracy; + document.getElementById('timestamp').innerHTML = date.toDateString() + " " + date.toTimeString(); + } + + /******************************************************************************/ + + var location_div = '<div id="info">' + + '<b>Status:</b> <span id="location_status">Stopped</span>' + + '<table width="100%">', + latitude = '<tr>' + + '<td><b>Latitude:</b></td>' + + '<td id="latitude"> </td>' + + '<td>(decimal degrees) geographic coordinate [<a href="http://dev.w3.org/geo/api/spec-source.html#lat">#ref]</a></td>' + + '</tr>', + longitude = '<tr>' + + '<td><b>Longitude:</b></td>' + + '<td id="longitude"> </td>' + + '<td>(decimal degrees) geographic coordinate [<a href="http://dev.w3.org/geo/api/spec-source.html#lat">#ref]</a></td>' + + '</tr>', + altitude = '<tr>' + + '<td><b>Altitude:</b></td>' + + '<td id="altitude"> </td>' + + '<td>null if not supported;<br>' + + '(meters) height above the [<a href="http://dev.w3.org/geo/api/spec-source.html#ref-wgs">WGS84</a>] ellipsoid. [<a href="http://dev.w3.org/geo/api/spec-source.html#altitude">#ref]</a></td>' + + '</tr>', + accuracy = '<tr>' + + '<td><b>Accuracy:</b></td>' + + '<td id="accuracy"> </td>' + + '<td>(meters; non-negative; 95% confidence level) the accuracy level of the latitude and longitude coordinates. [<a href="http://dev.w3.org/geo/api/spec-source.html#accuracy">#ref]</a></td>' + + '</tr>', + heading = '<tr>' + + '<td><b>Heading:</b></td>' + + '<td id="heading"> </td>' + + '<td>null if not supported;<br>' + + 'NaN if speed == 0;<br>' + + '(degrees; 0° ≤ heading < 360°) direction of travel of the hosting device- counting clockwise relative to the true north. [<a href="http://dev.w3.org/geo/api/spec-source.html#heading">#ref]</a></td>' + + '</tr>', + speed = '<tr>' + + '<td><b>Speed:</b></td>' + + '<td id="speed"> </td>' + + '<td>null if not supported;<br>' + + '(meters per second; non-negative) magnitude of the horizontal component of the hosting device current velocity. [<a href="http://dev.w3.org/geo/api/spec-source.html#speed">#ref]</a></td>' + + '</tr>', + altitude_accuracy = '<tr>' + + '<td><b>Altitude Accuracy:</b></td>' + + '<td id="altitude_accuracy"> </td>' + + '<td>null if not supported;<br>(meters; non-negative; 95% confidence level) the accuracy level of the altitude. [<a href="http://dev.w3.org/geo/api/spec-source.html#altitude-accuracy">#ref]</a></td>' + + '</tr>', + time = '<tr>' + + '<td><b>Time:</b></td>' + + '<td id="timestamp"> </td>' + + '<td>(DOMTimeStamp) when the position was acquired [<a href="http://dev.w3.org/geo/api/spec-source.html#timestamp">#ref]</a></td>' + + '</tr>' + + '</table>' + + '</div>', + actions = + '<h2>Use Built-in WebView navigator.geolocation</h2>' + + '<div id="built-in-getLocation"></div>' + + 'Expected result: Will update all applicable values in status box for current location. Status will read Retrieving Location (may not see this if location is retrieved immediately) then Done.' + + '<p/> <div id="built-in-watchLocation"></div>' + + 'Expected result: Will update all applicable values in status box for current location and update as location changes. Status will read Running.' + + '<p/> <div id="built-in-stopLocation"></div>' + + 'Expected result: Will stop watching the location so values will not be updated. Status will read Stopped.' + + '<p/> <div id="built-in-getOld"></div>' + + 'Expected result: Will update location values with a cached position that is up to 30 seconds old. Verify with time value. Status will read Done.' + + '<h2>Use Cordova Geolocation Plugin</h2>' + + '<div id="cordova-getLocation"></div>' + + 'Expected result: Will update all applicable values in status box for current location. Status will read Retrieving Location (may not see this if location is retrieved immediately) then Done.' + + '<p/> <div id="cordova-watchLocation"></div>' + + 'Expected result: Will update all applicable values in status box for current location and update as location changes. Status will read Running.' + + '<p/> <div id="cordova-stopLocation"></div>' + + 'Expected result: Will stop watching the location so values will not be updated. Status will read Stopped.' + + '<p/> <div id="cordova-getOld"></div>' + + 'Expected result: Will update location values with a cached position that is up to 30 seconds old. Verify with time value. Status will read Done.', + values_info = + '<h3>Details about each value are listed below in the status box</h3>', + note = + '<h3>Allow use of current location, if prompted</h3>'; + + contentEl.innerHTML = values_info + location_div + latitude + longitude + altitude + accuracy + heading + speed + + altitude_accuracy + time + note + actions; + + createActionButton('Get Location', function () { + getLocation(false); + }, 'built-in-getLocation'); + + createActionButton('Start Watching Location', function () { + watchLocation(false); + }, 'built-in-watchLocation'); + + createActionButton('Stop Watching Location', function () { + stopLocation(false); + }, 'built-in-stopLocation'); + + createActionButton('Get Location Up to 30 Sec Old', function () { + getLocation(false, { maximumAge: 30000 }); + }, 'built-in-getOld'); + + createActionButton('Get Location', function () { + getLocation(true); + }, 'cordova-getLocation'); + + createActionButton('Start Watching Location', function () { + watchLocation(true); + }, 'cordova-watchLocation'); + + createActionButton('Stop Watching Location', function () { + stopLocation(true); + }, 'cordova-stopLocation'); + + createActionButton('Get Location Up to 30 Sec Old', function () { + getLocation(true, { maximumAge: 30000 }); + }, 'cordova-getOld'); +}; diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/www/Coordinates.js b/StoneIsland/plugins/cordova-plugin-geolocation/www/Coordinates.js new file mode 100644 index 00000000..84fdd5b8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/www/Coordinates.js @@ -0,0 +1,69 @@ +/* + * + * 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 class contains position information. + * @param {Object} lat + * @param {Object} lng + * @param {Object} alt + * @param {Object} acc + * @param {Object} head + * @param {Object} vel + * @param {Object} altacc + * @constructor + */ +var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) { + /** + * The latitude of the position. + */ + this.latitude = lat; + /** + * The longitude of the position, + */ + this.longitude = lng; + /** + * The accuracy of the position. + */ + this.accuracy = acc; + /** + * The altitude of the position. + */ + this.altitude = (alt !== undefined ? alt : null); + /** + * The direction the device is moving at the position. + */ + this.heading = (head !== undefined ? head : null); + /** + * The velocity with which the device is moving at the position. + */ + this.speed = (vel !== undefined ? vel : null); + + if (this.speed === 0 || this.speed === null) { + this.heading = NaN; + } + + /** + * The altitude accuracy of the position. + */ + this.altitudeAccuracy = (altacc !== undefined) ? altacc : null; +}; + +module.exports = Coordinates; diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/www/Position.js b/StoneIsland/plugins/cordova-plugin-geolocation/www/Position.js new file mode 100644 index 00000000..f0470dea --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/www/Position.js @@ -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. + * +*/ + +var Coordinates = require('./Coordinates'); + +var Position = function(coords, timestamp) { + if (coords) { + this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.velocity, coords.altitudeAccuracy); + } else { + this.coords = new Coordinates(); + } + this.timestamp = (timestamp !== undefined) ? timestamp : new Date(); +}; + +module.exports = Position; diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/www/PositionError.js b/StoneIsland/plugins/cordova-plugin-geolocation/www/PositionError.js new file mode 100644 index 00000000..9403f11f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/www/PositionError.js @@ -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. + * +*/ + +/** + * Position error object + * + * @constructor + * @param code + * @param message + */ +var PositionError = function(code, message) { + this.code = code || null; + this.message = message || ''; +}; + +PositionError.PERMISSION_DENIED = 1; +PositionError.POSITION_UNAVAILABLE = 2; +PositionError.TIMEOUT = 3; + +module.exports = PositionError; diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/www/blackberry10/GeolocationProxy.js b/StoneIsland/plugins/cordova-plugin-geolocation/www/blackberry10/GeolocationProxy.js new file mode 100644 index 00000000..0bba2263 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/www/blackberry10/GeolocationProxy.js @@ -0,0 +1,69 @@ +/* + * + * 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 idsMap = {}, + geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + +module.exports = { + + getLocation: function(success, error, args) { + var successCallback = function (result) { + var pos = result.coords; + pos.timestamp = result.timestamp; + if (success) { + success(pos); + } + }; + geo.getCurrentPosition(successCallback, error, { + enableHighAccuracy: args[0], + maximumAge: args[1] + }); + }, + + addWatch: function(success, error, args) { + var id = args[0], + successCallback = function (result) { + var pos = result.coords; + pos.timestamp = result.timestamp; + if (success) { + success(pos); + } + }, + nativeId = geo.watchPosition(successCallback, error, { + enableHighAccuracy: args[1] + }); + idsMap[id] = nativeId; + }, + + clearWatch: function(success, error, args) { + var id = args[0]; + if(id in idsMap) { + geo.clearWatch(idsMap[id]); + delete idsMap[id]; + } + if(success) { + success(); + } + } + +}; + +require("cordova/exec/proxy").add("Geolocation", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-geolocation/www/geolocation.js b/StoneIsland/plugins/cordova-plugin-geolocation/www/geolocation.js new file mode 100644 index 00000000..3814919a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-geolocation/www/geolocation.js @@ -0,0 +1,211 @@ +/* + * + * 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'), + utils = require('cordova/utils'), + exec = require('cordova/exec'), + PositionError = require('./PositionError'), + Position = require('./Position'); + +var timers = {}; // list of timers in use + +// Returns default params, overrides if provided with values +function parseParameters(options) { + var opt = { + maximumAge: 0, + enableHighAccuracy: false, + timeout: Infinity + }; + + if (options) { + if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) { + opt.maximumAge = options.maximumAge; + } + if (options.enableHighAccuracy !== undefined) { + opt.enableHighAccuracy = options.enableHighAccuracy; + } + if (options.timeout !== undefined && !isNaN(options.timeout)) { + if (options.timeout < 0) { + opt.timeout = 0; + } else { + opt.timeout = options.timeout; + } + } + } + + return opt; +} + +// Returns a timeout failure, closed over a specified timeout value and error callback. +function createTimeout(errorCallback, timeout) { + var t = setTimeout(function() { + clearTimeout(t); + t = null; + errorCallback({ + code:PositionError.TIMEOUT, + message:"Position retrieval timed out." + }); + }, timeout); + return t; +} + +var geolocation = { + lastPosition:null, // reference to last known (cached) position returned + /** + * Asynchronously acquires the current position. + * + * @param {Function} successCallback The function to call when the position data is available + * @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL) + * @param {PositionOptions} options The options for getting the position data. (OPTIONAL) + */ + getCurrentPosition:function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); + options = parseParameters(options); + + // Timer var that will fire an error callback if no position is retrieved from native + // before the "timeout" param provided expires + var timeoutTimer = {timer:null}; + + var win = function(p) { + clearTimeout(timeoutTimer.timer); + if (!(timeoutTimer.timer)) { + // Timeout already happened, or native fired error callback for + // this geo request. + // Don't continue with success callback. + return; + } + var pos = new Position( + { + latitude:p.latitude, + longitude:p.longitude, + altitude:p.altitude, + accuracy:p.accuracy, + heading:p.heading, + velocity:p.velocity, + altitudeAccuracy:p.altitudeAccuracy + }, + (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))) + ); + geolocation.lastPosition = pos; + successCallback(pos); + }; + var fail = function(e) { + clearTimeout(timeoutTimer.timer); + timeoutTimer.timer = null; + var err = new PositionError(e.code, e.message); + if (errorCallback) { + errorCallback(err); + } + }; + + // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just + // fire the success callback with the cached position. + if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) { + successCallback(geolocation.lastPosition); + // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object. + } else if (options.timeout === 0) { + fail({ + code:PositionError.TIMEOUT, + message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter." + }); + // Otherwise we have to call into native to retrieve a position. + } else { + if (options.timeout !== Infinity) { + // If the timeout value was not set to Infinity (default), then + // set up a timeout function that will fire the error callback + // if no successful position was retrieved before timeout expired. + timeoutTimer.timer = createTimeout(fail, options.timeout); + } else { + // This is here so the check in the win function doesn't mess stuff up + // may seem weird but this guarantees timeoutTimer is + // always truthy before we call into native + timeoutTimer.timer = true; + } + exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]); + } + return timeoutTimer; + }, + /** + * Asynchronously watches the geolocation for changes to geolocation. When a change occurs, + * the successCallback is called with the new location. + * + * @param {Function} successCallback The function to call each time the location data is available + * @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL) + * @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL) + * @return String The watch id that must be passed to #clearWatch to stop watching. + */ + watchPosition:function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); + options = parseParameters(options); + + var id = utils.createUUID(); + + // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition + timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options); + + var fail = function(e) { + clearTimeout(timers[id].timer); + var err = new PositionError(e.code, e.message); + if (errorCallback) { + errorCallback(err); + } + }; + + var win = function(p) { + clearTimeout(timers[id].timer); + if (options.timeout !== Infinity) { + timers[id].timer = createTimeout(fail, options.timeout); + } + var pos = new Position( + { + latitude:p.latitude, + longitude:p.longitude, + altitude:p.altitude, + accuracy:p.accuracy, + heading:p.heading, + velocity:p.velocity, + altitudeAccuracy:p.altitudeAccuracy + }, + (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))) + ); + geolocation.lastPosition = pos; + successCallback(pos); + }; + + exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]); + + return id; + }, + /** + * Clears the specified heading watch. + * + * @param {String} id The ID of the watch returned from #watchPosition + */ + clearWatch:function(id) { + if (id && timers[id] !== undefined) { + clearTimeout(timers[id].timer); + timers[id].timer = false; + exec(null, null, "Geolocation", "clearWatch", [id]); + } + } +}; + +module.exports = geolocation; diff --git a/StoneIsland/plugins/cordova-plugin-network-information/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-network-information/CONTRIBUTING.md new file mode 100644 index 00000000..f7dbcaba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-network-information/LICENSE b/StoneIsland/plugins/cordova-plugin-network-information/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/NOTICE b/StoneIsland/plugins/cordova-plugin-network-information/NOTICE new file mode 100644 index 00000000..fb19cbdb --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/NOTICE @@ -0,0 +1,8 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +This product includes software developed by Apple Inc. License can be found in the header of the affected files. (src/ios/CDVReachability.h, src/ios/CDVReachability.m) + diff --git a/StoneIsland/plugins/cordova-plugin-network-information/README.md b/StoneIsland/plugins/cordova-plugin-network-information/README.md new file mode 100644 index 00000000..c78f3b02 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/README.md @@ -0,0 +1,208 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +This plugin provides an implementation of an old version of the +[Network Information API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). +It provides information about the device's cellular and +wifi connection, and whether the device has an internet connection. + +## Installation + + cordova plugin add cordova-plugin-network-information + +## Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Browser +- iOS +- Windows Phone 7 and 8 +- Tizen +- Windows +- Firefox OS + +# Connection + +> The `connection` object, exposed via `navigator.connection`, provides information about the device's cellular and wifi connection. + +## Properties + +- connection.type + +## Constants + +- Connection.UNKNOWN +- Connection.ETHERNET +- Connection.WIFI +- Connection.CELL_2G +- Connection.CELL_3G +- Connection.CELL_4G +- Connection.CELL +- Connection.NONE + +## connection.type + +This property offers a fast way to determine the device's network +connection state, and type of connection. + +### Quick Example + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API Change + +Until Cordova 2.3.0, the `Connection` object was accessed via +`navigator.network.connection`, after which it was changed to +`navigator.connection` to match the W3C specification. It's still +available at its original location, but is deprecated and will +eventually be removed. + +### iOS Quirks + +- iOS can't detect the type of cellular network connection. + - `navigator.connection.type` is set to `Connection.CELL` for all cellular data. + +### Windows Phone Quirks + +- When running in the emulator, always detects `navigator.connection.type` as `Connection.UNKNOWN`. + +- Windows Phone can't detect the type of cellular network connection. + - `navigator.connection.type` is set to `Connection.CELL` for all cellular data. + +### Windows Quirks + +- When running in the Phone 8.1 emulator, always detects `navigator.connection.type` as `Connection.ETHERNET`. + +### Tizen Quirks + +- Tizen can only detect a WiFi or cellular connection. + - `navigator.connection.type` is set to `Connection.CELL_2G` for all cellular data. + +### Firefox OS Quirks + +- Firefox OS can't detect the type of cellular network connection. + - `navigator.connection.type` is set to `Connection.CELL` for all cellular data. + +### Browser Quirks + +- Browser can't detect the type of network connection. +`navigator.connection.type` is always set to `Connection.UNKNOWN` when online. + +# Network-related Events + +## offline + +The event fires when an application goes offline, and the device is +not connected to the Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + +### Details + +The `offline` event fires when a previously connected device loses a +network connection so that an application can no longer access the +Internet. It relies on the same information as the Connection API, +and fires when the value of `connection.type` becomes `NONE`. + +Applications typically should use `document.addEventListener` to +attach an event listener once the `deviceready` event fires. + +### Quick Example + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS Quirks + +During initial startup, the first offline event (if applicable) takes at least a second to fire. + +### Windows Phone 7 Quirks + +When running in the Emulator, the `connection.status` is always unknown, so this event does _not_ fire. + +### Windows Phone 8 Quirks + +The Emulator reports the connection type as `Cellular`, which does not change, so the event does _not_ fire. + +## online + +This event fires when an application goes online, and the device +becomes connected to the Internet. + + document.addEventListener("online", yourCallbackFunction, false); + +### Details + +The `online` event fires when a previously unconnected device receives +a network connection to allow an application access to the Internet. +It relies on the same information as the Connection API, +and fires when the `connection.type` changes from `NONE` to any other +value. + +Applications typically should use `document.addEventListener` to +attach an event listener once the `deviceready` event fires. + +### Quick Example + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS Quirks + +During initial startup, the first `online` event (if applicable) takes +at least a second to fire, prior to which `connection.type` is +`UNKNOWN`. + +### Windows Phone 7 Quirks + +When running in the Emulator, the `connection.status` is always unknown, so this event does _not_ fire. + +### Windows Phone 8 Quirks + +The Emulator reports the connection type as `Cellular`, which does not change, so events does _not_ fire. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-network-information/RELEASENOTES.md new file mode 100644 index 00000000..06bc5090 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/RELEASENOTES.md @@ -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. +# +--> +# Release Notes + +### 0.2.1 (Sept 5, 2013) +* CB-4432 copyright notice change + +### 0.2.3 (Sept 25, 2013) +* CB-4889 bumping&resetting version +* [windows8] commandProxy was moved +* CB-4889 renaming org.apache.cordova.core.network-information to org.apache.cordova.network-information +* removed duplicate comment line from plugin.xml +* added Network APIs for FirefoxOS +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4752] Incremented plugin version on dev branch. + +### 0.2.4 (Oct 28, 2013) +* CB-5128: add repo + issue tag to plugin.xml for network information plugin +* [CB-4915] Incremented plugin version on dev branch. + +### 0.2.5 (Dec 4, 2013) +* [ubuntu] specify policy_group +* add ubuntu platform +* Added amazon-fireos platform. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos' + +### 0.2.6 (Jan 02, 2014) +* CB-5658 Add doc/index.md for netinfo plugin + +### 0.2.7 (Feb 05, 2014) +* Initial implementation of Tizen plugin. + +### 0.2.8 (Apr 17, 2014) +* CB-6342: [iOS] iOS reports a cellular connection even when in Airplane mode +* CB-6422: [windows8] use cordova/exec/proxy +* CB-6460: Update license headers +* CB-6465: Add license headers to Tizen code +* Add NOTICE file + +### 0.2.9 (Jun 05, 2014) +* updated notice file to include missing license +* Cached extra info to better detect changes. +* CB-6809 Add license to CONTRIBUTING.md +* CB-6491 add CONTRIBUTING.md +* CB-6350 - Fix networkStatusForFlags return value type to work with 64-bit iOS (closes #8) +* Initial version of firefox os network information plugin +* there was an error in the object definition + +### 0.2.10 (Jun 24, 2014) +* CB-6907: [android] Don't crash on startup if no networks available + +### 0.2.11 (Aug 06, 2014) +* **FFOS** update NetworkProxy.js +* CB-6127 Updated translations for docs +* CB-7019 Updated version and RELEASENOTES.md for release 0.2.10 +* Fixed docs for online/offline event being backwards + +### 0.2.12 (Sep 17, 2014) +* CB-7471 cordova-plugin-network-information documentation translation +* Fix network information type exception on fxos 2 +* Added support for the browser +* CB-6724 added documentation for manual tests +* remove reference to test assets, they are optional +* Renamed test dir and added nested plugin.xml +* CB-6964 ported manual tests +* Port network tests to plugin-test-framework +* Fix naviagtor typo + +### 0.2.13 (Oct 03, 2014) +* CB-7595: Android L changes the type from Mobile to Cellular, I'm pretty sure this isn't documented + +### 0.2.14 (Dec 02, 2014) +* CB-7976 **Android**: Use webView's context rather than Activity's context for intent receiver +* CB-7700 cordova-plugin-network-information documentation translation: cordova-plugin-network-information + +### 0.2.15 (Feb 04, 2015) +* CB-8384 Network status change support on Windows +* CB-8384 Fixes the way we detect online status on Windows +* CB-8384 Add Windows platform quirks +* CB-8384 Add Windows section to Network Information plugin + +### 1.0.0 (Apr 15, 2015) +* CB-8746 gave plugin major version bump +* CB-8683 changed plugin-id to pacakge-name +* CB-8653 properly updated translated docs to use new id +* CB-8653 updated translated docs to use new id +* CB-8185 Fixes typo in `cordova.platformId` +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* CB-8185 Use `navigator.onLine` as connection information source on browser platform +* CB-8653 Updated Readme +* CB-8659: ios: 4.0.x Compatibility: Remove use of initWebView method +* CB-8573 Integrate TravisCI +* CB-8438 cordova-plugin-network-information documentation translation: cordova-plugin-network-information +* CB-8538 Added package.json file + +### 1.0.1 (Jun 17, 2015) +* Adding .ratignore file. +* CB-9128 cordova-plugin-network-information documentation translation: cordova-plugin-network-information +* fix npm md issue diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/de/README.md new file mode 100644 index 00000000..f6292b27 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/de/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +Dieses Plugin stellt eine Implementierung einer alten Version der [Netzwerk-Informationen-API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Es werden Informationen über das Gerät Mobilfunk und Wifi-Anschluss, und ob das Gerät über eine Internetverbindung verfügt. + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Browser + * iOS + * Windows Phone 7 und 8 + * Tizen + * Windows + * Firefox OS + +# Connection + +> Das `connection` Objekt, verfügbar gemachten über `navigator.connection`, enthält Informationen über die Mobilfunk- und Wi-Fi-Verbindung des Gerätes. + +## Eigenschaften + + * connection.type + +## Konstanten + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Diese Eigenschaft bietet eine schnelle Möglichkeit, um den Netzwerkverbindungsstatus und die Art der Verbindung zu bestimmen. + +### Kurzes Beispiel + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API Änderung + +Bis Cordova 2.3.0 wurde auf das `Connection` Objekt über `navigator.network.connection` zugegriffen, danach wurde der Zugriff auf `navigator.connection` geändert, um der W3C-Spezifikation zu entsprechen. Es steht immer noch an seiner ursprünglichen Stelle, aber ist veraltet und wird schliesslich entfernt. + +### iOS Macken + + * iOS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows Phone Macken + + * Wenn im Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als`Connection.UNKNOWN`. + + * Windows Phone kann Mobilfunknetz Verbindungstyp nicht erkennen. + + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows-Eigenheiten + + * Wenn im Telefon 8.1 Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als `Connection.ETHERNET`. + +### Tizen Macken + + * Tizen kann nur ein WiFi oder Mobilfunkverbindung erkennen. + * `Navigator.Connection.Type` ist für alle Handy-Daten auf `Connection.CELL_2G` festgelegt. + +### Firefox OS Macken + + * Firefox-OS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Browser-Eigenheiten + + * Browser kann die Art der Netzwerkverbindung nicht erkennen. `navigator.connection.type` ist immer auf `Connection.UNKNOWN` beim online gesetzt. + +# Netzwerk-Veranstaltungen + +## offline + +Das Ereignis wird ausgelöst, wenn eine Anwendung offline geht, und das Gerät nicht mit dem Internet verbunden ist. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Details + +Das `offline` -Ereignis wird ausgelöst, wenn ein bereits angeschlossenes Gerät eine Netzwerkverbindung verliert, so dass eine Anwendung nicht mehr auf das Internet zugreifen kann. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn der Wert des `connection.type` wird`NONE`. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS Macken + +Beim ersten Start dauert das erste offline-Event (falls zutreffend) mindestens eine Sekunde zu schießen. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass das Ereignis *nicht* Feuer. + +## online + +Dieses Ereignis wird ausgelöst, wenn eine Anwendung online geht, und das Gerät wird mit dem Internet verbunden. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Details + +Das `online` -Ereignis wird ausgelöst, wenn ein zuvor unverbundenen Gerät eine Netzwerkverbindung zu einem Anwendung Zugriff auf das Internet empfängt. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn die `connection.type` ändert sich von `NONE` auf einen anderen Wert. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS Macken + +Beim ersten Start die erste `online` Ereignis (falls zutreffend) dauert mindestens eine Sekunde vor dem Feuer `connection.type` ist`UNKNOWN`. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass Ereignisse *nicht* Feuer.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/de/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/de/index.md new file mode 100644 index 00000000..537328a6 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/de/index.md @@ -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. +--> + +# cordova-plugin-network-information + +Dieses Plugin stellt eine Implementierung einer alten Version der [Netzwerk-Informationen-API][1]. Es werden Informationen über das Gerät Mobilfunk und Wifi-Anschluss, und ob das Gerät über eine Internetverbindung verfügt. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Browser +* iOS +* Windows Phone 7 und 8 +* Tizen +* Windows +* Firefox OS + +# Connection + +> Das `connection` Objekt, verfügbar gemachten über `navigator.connection`, enthält Informationen über die Mobilfunk- und Wi-Fi-Verbindung des Gerätes. + +## Eigenschaften + +* connection.type + +## Konstanten + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Diese Eigenschaft bietet eine schnelle Möglichkeit, um den Netzwerkverbindungsstatus und die Art der Verbindung zu bestimmen. + +### Kurzes Beispiel + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API Änderung + +Bis Cordova 2.3.0 wurde auf das `Connection` Objekt über `navigator.network.connection` zugegriffen, danach wurde der Zugriff auf `navigator.connection` geändert, um der W3C-Spezifikation zu entsprechen. Es steht immer noch an seiner ursprünglichen Stelle, aber ist veraltet und wird schliesslich entfernt. + +### iOS Macken + +* iOS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows Phone Macken + +* Wenn im Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als`Connection.UNKNOWN`. + +* Windows Phone kann Mobilfunknetz Verbindungstyp nicht erkennen. + + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows-Eigenheiten + +* Wenn im Telefon 8.1 Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als `Connection.ETHERNET`. + +### Tizen Macken + +* Tizen kann nur ein WiFi oder Mobilfunkverbindung erkennen. + * `Navigator.Connection.Type` ist für alle Handy-Daten auf `Connection.CELL_2G` festgelegt. + +### Firefox OS Macken + +* Firefox-OS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +# Netzwerk-Veranstaltungen + +## offline + +Das Ereignis wird ausgelöst, wenn eine Anwendung offline geht, und das Gerät nicht mit dem Internet verbunden ist. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Details + +Das `offline` -Ereignis wird ausgelöst, wenn ein bereits angeschlossenes Gerät eine Netzwerkverbindung verliert, so dass eine Anwendung nicht mehr auf das Internet zugreifen kann. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn der Wert des `connection.type` wird`NONE`. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS Macken + +Beim ersten Start dauert das erste offline-Event (falls zutreffend) mindestens eine Sekunde zu schießen. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass das Ereignis *nicht* Feuer. + +## online + +Dieses Ereignis wird ausgelöst, wenn eine Anwendung online geht, und das Gerät wird mit dem Internet verbunden. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Details + +Das `online` -Ereignis wird ausgelöst, wenn ein zuvor unverbundenen Gerät eine Netzwerkverbindung zu einem Anwendung Zugriff auf das Internet empfängt. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn die `connection.type` ändert sich von `NONE` auf einen anderen Wert. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS Macken + +Beim ersten Start die erste `online` Ereignis (falls zutreffend) dauert mindestens eine Sekunde vor dem Feuer `connection.type` ist`UNKNOWN`. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass Ereignisse *nicht* Feuer. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/es/README.md new file mode 100644 index 00000000..4e30593d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/es/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +Este plugin proporciona una implementación de una versión antigua de la [Red de información API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Proporciona información acerca del dispositivo móvil y conexión wifi, y si el dispositivo tiene una conexión a internet. + +## Instalación + + cordova plugin add cordova-plugin-network-information + + +## Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Explorador + * iOS + * Windows Phone 7 y 8 + * Tizen + * Windows + * Firefox OS + +# Connection + +> El objeto de `connection`, expuesto a través de `navigator.connection`, proporciona información sobre conexión celular y wifi del dispositivo. + +## Propiedades + + * connection.type + +## Constantes + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Esta propiedad ofrece una forma rápida de determinar el estado de conexión de red del dispositivo y el tipo de conexión. + +### Ejemplo rápido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambio de API + +Hasta Cordova 2.3.0, el objeto de `conexión` era acceder a través de `navigator.network.connection`, tras lo cual fue cambiada a `navigator.connection` para que coincida con la especificación del W3C. Sigue estando disponible en su ubicación original, pero es obsoleto y eventualmente desaparecerá. + +### iOS rarezas + + * iOS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows Phone rarezas + + * Cuando se ejecuta en el emulador, siempre detecta `navigator.connection.type` como `Connection.UNKNOWN`. + + * Windows Phone no puede detectar el tipo de conexión de red celular. + + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows rarezas + + * Cuando se ejecuta en el emulador de teléfono 8.1, siempre detecta `navigator.connection.type` como`Connection.ETHERNET`. + +### Rarezas Tizen + + * Tizen sólo puede detectar un Wi-Fi o conexión celular. + * `navigator.connection.type`se establece en `Connection.CELL_2G` para todos los datos celulares. + +### Firefox OS rarezas + + * Firefox OS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Navegador rarezas + + * Navegador no puede detectar el tipo de conexión de red. `Navigator.Connection.Type` se encuentra siempre a `Connection.UNKNOWN` cuando en lÃnea. + +# Eventos relacionados con la red + +## offline + +El evento se desencadena cuando una aplicación está desconectada, y el dispositivo no está conectado a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Detalles + +El evento `offline` se desencadena cuando un dispositivo conectado previamente pierde una conexión de red para que una aplicación no puede acceder a Internet. Se basa en la misma información que la API de conexión y cuando se dispara el valor del `connection.type` se convierte`NONE`. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento offline (si es aplicable) tarda al menos un segundo en fuego. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, asà que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador informa el tipo de conexión como `celular`, que no cambia, asà que el evento *no se* fuego. + +## online + +Este evento se desencadena cuando una aplicación va en lÃnea, y el dispositivo se conecta a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Detalles + +El evento `online` se desencadena cuando un dispositivo previamente inconexos recibe una conexión de red para permitir un acceso a las aplicaciones para Internet. Se basa en la misma información que la API de conexión y se desencadena cuando el `connection.type` cambia de `ninguno` a cualquier otro valor. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento `en lÃnea` (si procede) al menos toma un segundo para disparar, antes de que `connection.type` es `desconocido`. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, asà que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador, informa el tipo de conexión como `Cellular` , que no cambia, asà que se lo eventos *no* fuego.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/es/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/es/index.md new file mode 100644 index 00000000..65158ef5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/es/index.md @@ -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. +--> + +# cordova-plugin-network-information + +Este plugin proporciona una implementación de una versión antigua de la [Red de información API][1]. Proporciona información acerca del dispositivo móvil y conexión wifi, y si el dispositivo tiene una conexión a internet. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Instalación + + cordova plugin add cordova-plugin-network-information + + +## Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Explorador +* iOS +* Windows Phone 7 y 8 +* Tizen +* Windows +* Firefox OS + +# Conexión + +> El objeto de `connection`, expuesto a través de `navigator.connection`, proporciona información sobre conexión celular y wifi del dispositivo. + +## Propiedades + +* connection.type + +## Constantes + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_4G +* Connection.CELL_3G +* Connection.CELL +* Connection.NONE + +## connection.type + +Esta propiedad ofrece una forma rápida de determinar el estado de conexión de red del dispositivo y el tipo de conexión. + +### Ejemplo rápido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambio de API + +Hasta Cordova 2.3.0, el objeto de `conexión` era acceder a través de `navigator.network.connection`, tras lo cual fue cambiada a `navigator.connection` para que coincida con la especificación del W3C. Sigue estando disponible en su ubicación original, pero es obsoleto y eventualmente desaparecerá. + +### iOS rarezas + +* iOS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows Phone rarezas + +* Cuando se ejecuta en el emulador, siempre detecta `navigator.connection.type` como `Connection.UNKNOWN`. + +* Windows Phone no puede detectar el tipo de conexión de red celular. + + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows rarezas + +* Cuando se ejecuta en el emulador de teléfono 8.1, siempre detecta `navigator.connection.type` como`Connection.ETHERNET`. + +### Rarezas Tizen + +* Tizen sólo puede detectar un Wi-Fi o conexión celular. + * `navigator.connection.type`se establece en `Connection.CELL_2G` para todos los datos celulares. + +### Firefox OS rarezas + +* Firefox OS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type`se establece en `Connection.CELL` para todos los datos celulares. + +# Eventos relacionados con la red + +## offline + +El evento se desencadena cuando una aplicación está desconectada, y el dispositivo no está conectado a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Detalles + +El evento `offline` se desencadena cuando un dispositivo conectado previamente pierde una conexión de red para que una aplicación no puede acceder a Internet. Se basa en la misma información que la API de conexión y cuando se dispara el valor del `connection.type` se convierte`NONE`. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento offline (si es aplicable) tarda al menos un segundo en fuego. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, asà que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador informa el tipo de conexión como `celular`, que no cambia, asà que el evento *no se* fuego. + +## online + +Este evento se desencadena cuando una aplicación va en lÃnea, y el dispositivo se conecta a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Detalles + +El evento `online` se desencadena cuando un dispositivo previamente inconexos recibe una conexión de red para permitir un acceso a las aplicaciones para Internet. Se basa en la misma información que la API de conexión y se desencadena cuando el `connection.type` cambia de `ninguno` a cualquier otro valor. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento `en lÃnea` (si procede) al menos toma un segundo para disparar, antes de que `connection.type` es `desconocido`. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, asà que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador, informa el tipo de conexión como `Cellular` , que no cambia, asà que se lo eventos *no* fuego. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/fr/README.md new file mode 100644 index 00000000..8f2b82cc --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/fr/README.md @@ -0,0 +1,188 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +Ce plugin fournit une implémentation d'une ancienne version de l' [API Information Network](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Il fournit des informations sur l'appareil cellulaire et connexion wifi, et si l'appareil dispose d'une connexion internet. + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Navigateur + * iOS + * Windows Phone 7 et 8 + * Paciarelli + * Windows + * Firefox OS + +# Connexion + +> L'objet `connection`, disponible via `navigator.connection`, fournit des informations sur la connection cellulaire/wifi de l'appareil. + +## Propriétés + + * connection.type + +## Constantes + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Cette propriété offre un moyen rapide pour déterminer l'état et le type de la connexion réseau de l'appareil. + +### Exemple court + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Changement d'API + +Jusqu'à Cordova 2.3.0, l'objet `Connection` était accessible via `navigator.network.connection` ; ceci a été changé pour `navigator.connection` afin de concorder avec la spécification du W3C. L'accès est toujours possible à l'emplacement d'origine, mais est considéré comme obsolète et sera bientôt supprimé. + +### Notes au sujet d'iOS + + * iOS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Windows Phone Quirks + + * Lors de l'exécution dans l'émulateur, détecte toujours `navigator.connection.type` comme`Connection.UNKNOWN`. + + * Windows Phone ne peut pas détecter le type de connexion au réseau cellulaire. + + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Bizarreries de Windows + + * Lors de l'exécution dans l'émulateur de téléphone 8.1, `Connection.ETHERNET` détecte toujours `navigator.connection.type`. + +### Bizarreries de paciarelli + + * Paciarelli ne peut détecter une connexion cellulaire ou le WiFi. + * `navigator.connection.type` a la valeur `Connection.CELL_2G` pour toutes les données cellulaires. + +### Firefox OS Quirks + + * Firefox OS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Bizarreries navigateur + + * Navigateur ne peut pas détecter le type de connexion réseau. `navigator.connection.type` est toujours définie sur `Connection.UNKNOWN` en ligne. + +# Événements liés au réseau + +## offline + +L'évènement se déclenche lorsqu'une application se déconnecte, quand l'appareil n'est pas connecté à Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Détails + +L'évènement `offline` se déclenche lorsqu'un appareil précédemment connecté perd sa connexion au réseau, empêchant ainsi l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche lorsque la valeur de `connection.type` devient`NONE`. + +Les applications devraient en général utiliser `document.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché. + +### Exemple court + + document.addEventListener (« hors ligne », onOffline, false) ; + + function onOffline() {/ / gestion de l'événement en mode hors connexion} + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement offline (si applicable) prend au moins une seconde. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular`, type qui ne change jamais, ainsi l'évènement n'est *pas* déclenché. + +## online + +L'évènement se déclenche lorsqu'une application se connecte, quand l'appareil est connecté à Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Détails + +L'évènement `online` se déclenche lorsqu'un appareil précédemment non-connecté se connecte au réseau, permettant ainsi à l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche quand le `connection.type` passe de `NONE` à une autre valeur. + +Les applications devraient en général utiliser `document.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché. + +### Exemple court + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement `online` (si applicable) prend au moins une seconde avant quoi `connection.type` vaut `UNKNOWN`. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular` , qui ne change pas, aussi des événements ne fait *pas* de feu.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/fr/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/fr/index.md new file mode 100644 index 00000000..e49c5d52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/fr/index.md @@ -0,0 +1,184 @@ +<!--- + 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-plugin-network-information + +Ce plugin fournit une implémentation d'une ancienne version de l' [API Information Network][1]. Il fournit des informations sur l'appareil cellulaire et connexion wifi, et si l'appareil dispose d'une connexion internet. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Navigateur +* iOS +* Windows Phone 7 et 8 +* Paciarelli +* Windows +* Firefox OS + +# Connexion + +> L'objet `connection`, disponible via `navigator.connection`, fournit des informations sur la connection cellulaire/wifi de l'appareil. + +## Propriétés + +* connection.type + +## Constantes + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Cette propriété offre un moyen rapide pour déterminer l'état et le type de la connexion réseau de l'appareil. + +### Petit exemple + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Changement d'API + +Jusqu'à Cordova 2.3.0, l'objet `Connection` était accessible via `navigator.network.connection` ; ceci a été changé pour `navigator.connection` afin de concorder avec la spécification du W3C. L'accès est toujours possible à l'emplacement d'origine, mais est considéré comme obsolète et sera bientôt supprimé. + +### iOS Quirks + +* iOS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Windows Phone Quirks + +* Lors de l'exécution dans l'émulateur, détecte toujours `navigator.connection.type` comme`Connection.UNKNOWN`. + +* Windows Phone ne peut pas détecter le type de connexion au réseau cellulaire. + + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Bizarreries de Windows + +* Lors de l'exécution dans l'émulateur de téléphone 8.1, `Connection.ETHERNET` détecte toujours `navigator.connection.type`. + +### Bizarreries de paciarelli + +* Paciarelli ne peut détecter une connexion cellulaire ou le WiFi. + * `navigator.connection.type` a la valeur `Connection.CELL_2G` pour toutes les données cellulaires. + +### Firefox OS Quirks + +* Firefox OS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type` a la valeur `Connection.CELL` pour toutes les données cellulaires. + +# Événements liés au réseau + +## offline + +L'évènement se déclenche lorsqu'une application se déconnecte, quand l'appareil n'est pas connecté à Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Détails + +L'évènement `offline` se déclenche lorsqu'un appareil précédemment connecté perd sa connexion au réseau, empêchant ainsi l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche lorsque la valeur de `connection.type` devient`NONE`. + +Les applications doivent généralement utiliser `document.addEventListener` pour attacher un écouteur d'événements une fois le `deviceready` événement se déclenche. + +### Exemple court + + document.addEventListener (« hors ligne », onOffline, false) ; + + function onOffline() {/ / gestion de l'événement en mode hors connexion} + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement offline (si applicable) prend au moins une seconde. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular`, type qui ne change jamais, ainsi l'évènement n'est *pas* déclenché. + +## online + +L'évènement se déclenche lorsqu'une application se connecte, quand l'appareil est connecté à Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Détails + +L'évènement `online` se déclenche lorsqu'un appareil précédemment non-connecté se connecte au réseau, permettant ainsi à l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche quand le `connection.type` passe de `NONE` à une autre valeur. + +Les applications doivent généralement utiliser `document.addEventListener` pour attacher un écouteur d'événements une fois le `deviceready` événement se déclenche. + +### Exemple court + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement `online` (si applicable) prend au moins une seconde avant quoi `connection.type` vaut `UNKNOWN`. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular` , qui ne change pas, aussi des événements ne fait *pas* de feu. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/it/README.md new file mode 100644 index 00000000..f4343594 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/it/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di informazioni di rete](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Fornisce informazioni sul dispositivo cellulare e connessione wifi, e se il dispositivo dispone di una connessione internet. + +## Installazione + + cordova plugin add cordova-plugin-network-information + + +## Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Browser + * iOS + * Windows Phone 7 e 8 + * Tizen + * Windows + * Firefox OS + +# Connessione + +> Il `connection` oggetto, esposto tramite `navigator.connection` , fornisce informazioni sulla connessione wifi e cellulare del dispositivo. + +## Proprietà + + * connection.type + +## Costanti + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Questa proprietà offre un modo rapido per determinare stato della connessione di rete del dispositivo e il tipo di connessione. + +### Esempio rapido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambiamento di API + +Fino a Cordova 2.3.0, il `Connection` oggetto era accessibile tramite `navigator.network.connection` , dopo che è stato cambiato in `navigator.connection` per abbinare la specifica W3C. È ancora disponibile nella sua posizione originale, ma è obsoleto e verrà rimosso alla fine. + +### iOS stranezze + + * iOS non è possibile rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows Phone + + * Quando è in esecuzione nell'emulatore, rileva sempre `navigator.connection.type` come`Connection.UNKNOWN`. + + * Windows Phone non riesce a rilevare il tipo di connessione di rete cellulare. + + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows + + * Quando è in esecuzione nell'emulatore Phone 8.1, sempre rileva `navigator.connection.type` come `Connection.ETHERNET`. + +### Tizen stranezze + + * Tizen può rilevare solo un WiFi o una connessione cellulare. + * `navigator.connection.type` è impostata su `Connection.CELL_2G` per tutti i dati cellulare. + +### Firefox OS stranezze + + * Sistema operativo Firefox non riesce a rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze browser + + * Browser non è in grado di rilevare il tipo di connessione di rete. `navigator.connection.type` è sempre impostata su `Connection.UNKNOWN` quando si è online. + +# Eventi relativi alla rete + +## offline + +L'evento viene generato quando un'applicazione passa alla modalità offline, e il dispositivo non è connesso a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Dettagli + +Il `offline` evento viene generato quando un dispositivo precedentemente connesso perde una connessione di rete in modo che un'applicazione non è più possibile accedere a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene generato quando il valore di `connection.type` diventa`NONE`. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo evento offline (se applicabile) richiede almeno un secondo al fuoco. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, così fa l'evento *non* fuoco. + +## online + +Questo evento viene generato quando un'applicazione va online, e il dispositivo diventa collegato a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Dettagli + +Il `online` evento viene generato quando un dispositivo precedentemente scollegato riceve una connessione di rete per consentire un'accesso di applicazione a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene attivato quando il `connection.type` cambia da `NONE` a qualsiasi altro valore. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo `online` evento (se applicabile) richiede almeno un secondo al fuoco, prima che `connection.type` è`UNKNOWN`. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, quindi, non gli eventi *non* a fuoco.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/it/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/it/index.md new file mode 100644 index 00000000..e1917195 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/it/index.md @@ -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. +--> + +# cordova-plugin-network-information + +Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di informazioni di rete][1]. Fornisce informazioni sul dispositivo cellulare e connessione wifi, e se il dispositivo dispone di una connessione internet. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Installazione + + cordova plugin add cordova-plugin-network-information + + +## Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Browser +* iOS +* Windows Phone 7 e 8 +* Tizen +* Windows +* Firefox OS + +# Connessione + +> Il `connection` oggetto, esposto tramite `navigator.connection` , fornisce informazioni sulla connessione wifi e cellulare del dispositivo. + +## Proprietà + +* connection.type + +## Costanti + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Questa proprietà offre un modo rapido per determinare stato della connessione di rete del dispositivo e il tipo di connessione. + +### Esempio rapido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambiamento di API + +Fino a Cordova 2.3.0, il `Connection` oggetto era accessibile tramite `navigator.network.connection` , dopo che è stato cambiato in `navigator.connection` per abbinare la specifica W3C. È ancora disponibile nella sua posizione originale, ma è obsoleto e verrà rimosso alla fine. + +### iOS stranezze + +* iOS non è possibile rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows Phone + +* Quando è in esecuzione nell'emulatore, rileva sempre `navigator.connection.type` come`Connection.UNKNOWN`. + +* Windows Phone non riesce a rilevare il tipo di connessione di rete cellulare. + + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows + +* Quando è in esecuzione nell'emulatore Phone 8.1, sempre rileva `navigator.connection.type` come `Connection.ETHERNET`. + +### Tizen stranezze + +* Tizen può rilevare solo un WiFi o una connessione cellulare. + * `navigator.connection.type` è impostata su `Connection.CELL_2G` per tutti i dati cellulare. + +### Firefox OS stranezze + +* Sistema operativo Firefox non riesce a rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +# Eventi relativi alla rete + +## offline + +L'evento viene generato quando un'applicazione passa alla modalità offline, e il dispositivo non è connesso a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Dettagli + +Il `offline` evento viene generato quando un dispositivo precedentemente connesso perde una connessione di rete in modo che un'applicazione non è più possibile accedere a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene generato quando il valore di `connection.type` diventa`NONE`. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo evento offline (se applicabile) richiede almeno un secondo al fuoco. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, così fa l'evento *non* fuoco. + +## online + +Questo evento viene generato quando un'applicazione va online, e il dispositivo diventa collegato a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Dettagli + +Il `online` evento viene generato quando un dispositivo precedentemente scollegato riceve una connessione di rete per consentire un'accesso di applicazione a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene attivato quando il `connection.type` cambia da `NONE` a qualsiasi altro valore. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo `online` evento (se applicabile) richiede almeno un secondo al fuoco, prima che `connection.type` è`UNKNOWN`. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, quindi, non gli eventi *non* a fuoco. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/ja/README.md new file mode 100644 index 00000000..797b7413 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/ja/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +ã“ã®ãƒ—ラグインã¯ã€å¤ã„ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã®[ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æƒ…å ± API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)ã®å®Ÿè£…ã‚’æä¾›ã—ã¾ã™ã€‚ デãƒã‚¤ã‚¹ã®æºå¸¯é›»è©±ã‚„ wifi 接続ã«é–¢ã™ã‚‹æƒ…å ±ã‚’æä¾›ã—ã€ã‹ã©ã†ã‹ã€ãƒ‡ãƒã‚¤ã‚¹ãŒã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«æŽ¥ç¶šã—ã¾ã™ã€‚ + +## インストール + + cordova plugin add cordova-plugin-network-information + + +## サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * ブラウザー + * iOS + * Windows Phone 7 㨠8 + * Tizen + * Windows + * Firefox ã® OS + +# Connection + +> `connection`オブジェクトã«ã‚ˆã£ã¦å…¬é–‹ã•れ㦠`navigator.connection` ã€ãƒ‡ãƒã‚¤ã‚¹ã®æºå¸¯é›»è©±ã‚„ wifi 接続ã«é–¢ã™ã‚‹æƒ…å ±ã‚’æä¾›ã—ã¾ã™ã€‚ + +## プãƒãƒ‘ティ + + * connection.type + +## 定数 + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +ã“ã®ãƒ—ãƒãƒ‘ティã¯ãƒ‡ãƒã‚¤ã‚¹ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šçŠ¶æ…‹ã‚’ç¢ºèªã™ã‚‹é€Ÿã„方法をæä¾›ã—ã€æŽ¥ç¶šã®ç¨®é¡žã€‚ + +### ç°¡å˜ãªä¾‹ + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API ã®å¤‰æ›´ + +コルドム2.3.0ã€ã¾ã§ã€ `Connection` 経由ã§ã‚¢ã‚¯ã‚»ã‚¹ã•れãŸã‚ªãƒ–ジェクト㌠`navigator.network.connection` ã€ãれã«å¤‰æ›´ã•れã¾ã—ãŸãŒå¾Œ `navigator.connection` W3C ã®ä»•様ã«ä¸€è‡´ã—ã¾ã™ã€‚ ãれã¯ã¾ã å…ƒã®å ´æ‰€ã¯å»ƒæ¢ã•ã‚Œã€æœ€çµ‚çš„ã«å‰Šé™¤ã•れã¾ã™ã€‚ + +### iOS ã®ç™– + + * iOS ã¯ã€æºå¸¯é›»è©±ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 + * `navigator.connection.type`è¨å®šã™ã‚‹ `Connection.CELL` ã™ã¹ã¦ã®æºå¸¯é›»è©±ãƒ‡ãƒ¼ã‚¿ã®ã€‚ + +### Windows Phone ã®ç™– + + * エミュレーターã§å®Ÿè¡Œã—ã¦ã„ã‚‹ã¨ãã‚’å¸¸ã«æ¤œå‡º `navigator.connection.type` ã¨ã—ã¦`Connection.UNKNOWN`. + + * Windows Phone æºå¸¯é›»è©±ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 + + * `navigator.connection.type`è¨å®šã™ã‚‹ `Connection.CELL` ã™ã¹ã¦ã®æºå¸¯é›»è©±ãƒ‡ãƒ¼ã‚¿ã®ã€‚ + +### Windows ã®ç™– + + * 電話 8.1 エミュレーターã§å®Ÿè¡Œã™ã‚‹å ´åˆã¯ã€å¸¸ã« `Connection.ETHERNET` ã¨ã—㦠`navigator.connection.type` を検出ã—ã¾ã™. + +### Tizen ã®ç™– + + * Tizen ã«ã¯ã€WiFi ã¾ãŸã¯æºå¸¯é›»è©±ã®æŽ¥ç¶šã ã‘を検出ã§ãã¾ã™ã€‚ + * `navigator.connection.type` ã¯ã€ã™ã¹ã¦ã®æºå¸¯é›»è©±ã®ãƒ‡ãƒ¼ã‚¿ã‚’ `Connection.CELL_2G` ã«è¨å®šã•れã¾ã™ã€‚ + +### Firefox OS ç™– + + * Firefox ã® OS ã¯ã€æºå¸¯é›»è©±ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 + * `navigator.connection.type`è¨å®šã™ã‚‹ `Connection.CELL` ã™ã¹ã¦ã®æºå¸¯é›»è©±ãƒ‡ãƒ¼ã‚¿ã®ã€‚ + +### ブラウザーã®ç™– + + * ブラウザーã¯ã€ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 `navigator.connection.type`ã¯ã€ `Connection.UNKNOWN`オンライン時ã«å¸¸ã«è¨å®šã•れã¾ã™ã€‚ + +# ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯é–¢é€£ã®ã‚¤ãƒ™ãƒ³ãƒˆ + +## offline + +アプリケーションãŒã‚ªãƒ•ラインã«ãªã‚Šã€ãƒ‡ãƒã‚¤ã‚¹ãŒã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«æŽ¥ç¶šã•れã¦ã„ãªã„ã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細 + +`offline`アプリケーションã¯ã‚‚ã¯ã‚„ã€ã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«ã‚¢ã‚¯ã‚»ã‚¹ã§ãるよã†ã«ã€ä»¥å‰æŽ¥ç¶šã•れãŸãƒ‡ãƒã‚¤ã‚¹ã¯ã€ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šãŒå¤±ã‚れãŸã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ 接続 API ã¨åŒã˜æƒ…å ±ã«ä¾å˜ã—ã¦ãŠã‚Šã€ç«ç½æ™‚ã®å€¤ `connection.type` ã«ãªã‚Šã¾ã™ã€‚`NONE`. + +通常アプリケーションã«ä½¿ç”¨ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ `document.addEventListener` 一度ã®ã‚¤ãƒ™ãƒ³ãƒˆ リスナーをアタッãƒã—〠`deviceready` イベントãŒç™ºç”Ÿã—ã¾ã™ã€‚ + +### ç°¡å˜ãªä¾‹ + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS ã®ç™– + +åˆå›žèµ·å‹•時 (当ã¦ã¯ã¾ã‚‹å ´åˆ) ã®æœ€åˆã®ã‚ªãƒ•ライン イベントã¯ç«ã« 1 秒以上ã‹ã‹ã‚Šã¾ã™ã€‚ + +### Windows Phone 7 ã®ç™– + +エミュレーターã§å®Ÿè¡Œã—ã¦ã„ã‚‹ã¨ã〠`connection.status` ã¯å¸¸ã«çŸ¥ã‚‰ã‚Œã¦ã„ã‚‹ã€ã“ã®ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ + +### Windows Phone 8 ç™– + +ã‚¨ãƒŸãƒ¥ãƒ¬ãƒ¼ã‚¿ãƒ¼ã¨æŽ¥ç¶šã®ç¨®é¡žã®ãƒ¬ãƒãƒ¼ãƒˆ `Cellular` ã¯å¤‰åŒ–ã—ã¾ã›ã‚“ã€ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ + +## online + +アプリケーションã¯ã€ã‚ªãƒ³ãƒ©ã‚¤ãƒ³ã«ãªã‚‹ã—ã€ãƒ‡ãƒã‚¤ã‚¹ãŒã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«æŽ¥ç¶šã™ã‚‹ã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細 + +`online`ä»¥å‰æŽ¥ç¶šã•れã¦ã„ãªã„デãƒã‚¤ã‚¹ãŒã€ã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã¸ã®ã‚¢ãƒ—リケーション アクセスを許å¯ã™ã‚‹ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã‚’å—ä¿¡ã™ã‚‹ã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ 接続 API ã¨åŒã˜æƒ…å ±ã«ä¾å˜ã—ã¦ãŠã‚Šã€å ´åˆã«é©ç”¨ã•れã¾ã™ã€ `connection.type` ã‹ã‚‰å¤‰æ›´ `NONE` 以外ã®å€¤ã«ã—ã¾ã™ã€‚ + +通常アプリケーションã«ä½¿ç”¨ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ `document.addEventListener` 一度ã®ã‚¤ãƒ™ãƒ³ãƒˆ リスナーをアタッãƒã—〠`deviceready` イベントãŒç™ºç”Ÿã—ã¾ã™ã€‚ + +### ç°¡å˜ãªä¾‹ + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS ã®ç™– + +åˆå›žèµ·å‹•時ã«ã¯ã€æœ€åˆã® `online` (当ã¦ã¯ã¾ã‚‹å ´åˆ) イベントãŒå°‘ãªãã¨ã‚‚ç«ã‚’å‰ã«ç¬¬ 2 `connection.type` ã¯`UNKNOWN`. + +### Windows Phone 7 ã®ç™– + +エミュレーターã§å®Ÿè¡Œã—ã¦ã„ã‚‹ã¨ã〠`connection.status` ã¯å¸¸ã«çŸ¥ã‚‰ã‚Œã¦ã„ã‚‹ã€ã“ã®ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ + +### Windows Phone 8 ç™– + +ã‚¨ãƒŸãƒ¥ãƒ¬ãƒ¼ã‚¿ãƒ¼ã¨æŽ¥ç¶šã®ç¨®é¡žã®ãƒ¬ãƒãƒ¼ãƒˆ `Cellular` ã¯å¤‰åŒ–ã—ã¾ã›ã‚“ã€ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/ja/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/ja/index.md new file mode 100644 index 00000000..71b6f82e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/ja/index.md @@ -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. +--> + +# cordova-plugin-network-information + +ã“ã®ãƒ—ラグインã¯ã€å¤ã„ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã®[ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æƒ…å ± API][1]ã®å®Ÿè£…ã‚’æä¾›ã—ã¾ã™ã€‚ デãƒã‚¤ã‚¹ã®æºå¸¯é›»è©±ã‚„ wifi 接続ã«é–¢ã™ã‚‹æƒ…å ±ã‚’æä¾›ã—ã€ã‹ã©ã†ã‹ã€ãƒ‡ãƒã‚¤ã‚¹ãŒã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«æŽ¥ç¶šã—ã¾ã™ã€‚ + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## インストール + + cordova plugin add cordova-plugin-network-information + + +## サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* ブラウザー +* iOS +* Windows Phone 7 㨠8 +* Tizen +* Windows +* Firefox ã® OS + +# Connection + +> `connection`オブジェクトã«ã‚ˆã£ã¦å…¬é–‹ã•れ㦠`navigator.connection` ã€ãƒ‡ãƒã‚¤ã‚¹ã®æºå¸¯é›»è©±ã‚„ wifi 接続ã«é–¢ã™ã‚‹æƒ…å ±ã‚’æä¾›ã—ã¾ã™ã€‚ + +## プãƒãƒ‘ティ + +* connection.type + +## 定数 + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +ã“ã®ãƒ—ãƒãƒ‘ティã¯ãƒ‡ãƒã‚¤ã‚¹ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šçŠ¶æ…‹ã‚’ç¢ºèªã™ã‚‹é€Ÿã„方法をæä¾›ã—ã€æŽ¥ç¶šã®ç¨®é¡žã€‚ + +### ç°¡å˜ãªä¾‹ + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API ã®å¤‰æ›´ + +コルドム2.3.0ã€ã¾ã§ã€ `Connection` 経由ã§ã‚¢ã‚¯ã‚»ã‚¹ã•れãŸã‚ªãƒ–ジェクト㌠`navigator.network.connection` ã€ãれã«å¤‰æ›´ã•れã¾ã—ãŸãŒå¾Œ `navigator.connection` W3C ã®ä»•様ã«ä¸€è‡´ã—ã¾ã™ã€‚ ãれã¯ã¾ã å…ƒã®å ´æ‰€ã¯å»ƒæ¢ã•ã‚Œã€æœ€çµ‚çš„ã«å‰Šé™¤ã•れã¾ã™ã€‚ + +### iOS ã®ç™– + +* iOS ã¯ã€æºå¸¯é›»è©±ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 + * `navigator.connection.type`è¨å®šã™ã‚‹ `Connection.CELL` ã™ã¹ã¦ã®æºå¸¯é›»è©±ãƒ‡ãƒ¼ã‚¿ã®ã€‚ + +### Windows Phone ã®ç™– + +* エミュレーターã§å®Ÿè¡Œã—ã¦ã„ã‚‹ã¨ãã‚’å¸¸ã«æ¤œå‡º `navigator.connection.type` ã¨ã—ã¦`Connection.UNKNOWN`. + +* Windows Phone æºå¸¯é›»è©±ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 + + * `navigator.connection.type`è¨å®šã™ã‚‹ `Connection.CELL` ã™ã¹ã¦ã®æºå¸¯é›»è©±ãƒ‡ãƒ¼ã‚¿ã®ã€‚ + +### Windows ã®ç™– + +* 電話 8.1 エミュレーターã§å®Ÿè¡Œã™ã‚‹å ´åˆã¯ã€å¸¸ã« `Connection.ETHERNET` ã¨ã—㦠`navigator.connection.type` を検出ã—ã¾ã™. + +### Tizen ã®ç™– + +* Tizen ã«ã¯ã€WiFi ã¾ãŸã¯æºå¸¯é›»è©±ã®æŽ¥ç¶šã ã‘を検出ã§ãã¾ã™ã€‚ + * `navigator.connection.type` ã¯ã€ã™ã¹ã¦ã®æºå¸¯é›»è©±ã®ãƒ‡ãƒ¼ã‚¿ã‚’ `Connection.CELL_2G` ã«è¨å®šã•れã¾ã™ã€‚ + +### Firefox OS ç™– + +* Firefox ã® OS ã¯ã€æºå¸¯é›»è©±ã®ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã®ç¨®é¡žã‚’検出ã§ãã¾ã›ã‚“。 + * `navigator.connection.type`è¨å®šã™ã‚‹ `Connection.CELL` ã™ã¹ã¦ã®æºå¸¯é›»è©±ãƒ‡ãƒ¼ã‚¿ã®ã€‚ + +# ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯é–¢é€£ã®ã‚¤ãƒ™ãƒ³ãƒˆ + +## offline + +アプリケーションãŒã‚ªãƒ•ラインã«ãªã‚Šã€ãƒ‡ãƒã‚¤ã‚¹ãŒã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«æŽ¥ç¶šã•れã¦ã„ãªã„ã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細 + +`offline`アプリケーションã¯ã‚‚ã¯ã‚„ã€ã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«ã‚¢ã‚¯ã‚»ã‚¹ã§ãるよã†ã«ã€ä»¥å‰æŽ¥ç¶šã•れãŸãƒ‡ãƒã‚¤ã‚¹ã¯ã€ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šãŒå¤±ã‚れãŸã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ 接続 API ã¨åŒã˜æƒ…å ±ã«ä¾å˜ã—ã¦ãŠã‚Šã€ç«ç½æ™‚ã®å€¤ `connection.type` ã«ãªã‚Šã¾ã™ã€‚`NONE`. + +通常アプリケーションã«ä½¿ç”¨ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ `document.addEventListener` 一度ã®ã‚¤ãƒ™ãƒ³ãƒˆ リスナーをアタッãƒã—〠`deviceready` イベントãŒç™ºç”Ÿã—ã¾ã™ã€‚ + +### ç°¡å˜ãªä¾‹ + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS ã®ç™– + +åˆå›žèµ·å‹•時 (当ã¦ã¯ã¾ã‚‹å ´åˆ) ã®æœ€åˆã®ã‚ªãƒ•ライン イベントã¯ç«ã« 1 秒以上ã‹ã‹ã‚Šã¾ã™ã€‚ + +### Windows Phone 7 ã®ç™– + +エミュレーターã§å®Ÿè¡Œã—ã¦ã„ã‚‹ã¨ã〠`connection.status` ã¯å¸¸ã«çŸ¥ã‚‰ã‚Œã¦ã„ã‚‹ã€ã“ã®ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ + +### Windows Phone 8 ç™– + +ã‚¨ãƒŸãƒ¥ãƒ¬ãƒ¼ã‚¿ãƒ¼ã¨æŽ¥ç¶šã®ç¨®é¡žã®ãƒ¬ãƒãƒ¼ãƒˆ `Cellular` ã¯å¤‰åŒ–ã—ã¾ã›ã‚“ã€ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ + +## online + +アプリケーションã¯ã€ã‚ªãƒ³ãƒ©ã‚¤ãƒ³ã«ãªã‚‹ã—ã€ãƒ‡ãƒã‚¤ã‚¹ãŒã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã«æŽ¥ç¶šã™ã‚‹ã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細 + +`online`ä»¥å‰æŽ¥ç¶šã•れã¦ã„ãªã„デãƒã‚¤ã‚¹ãŒã€ã‚¤ãƒ³ã‚¿ãƒ¼ãƒãƒƒãƒˆã¸ã®ã‚¢ãƒ—リケーション アクセスを許å¯ã™ã‚‹ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯æŽ¥ç¶šã‚’å—ä¿¡ã™ã‚‹ã¨ãã«ç™ºç”Ÿã—ã¾ã™ã€‚ 接続 API ã¨åŒã˜æƒ…å ±ã«ä¾å˜ã—ã¦ãŠã‚Šã€å ´åˆã«é©ç”¨ã•れã¾ã™ã€ `connection.type` ã‹ã‚‰å¤‰æ›´ `NONE` 以外ã®å€¤ã«ã—ã¾ã™ã€‚ + +通常アプリケーションã«ä½¿ç”¨ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ `document.addEventListener` 一度ã®ã‚¤ãƒ™ãƒ³ãƒˆ リスナーをアタッãƒã—〠`deviceready` イベントãŒç™ºç”Ÿã—ã¾ã™ã€‚ + +### ç°¡å˜ãªä¾‹ + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS ã®ç™– + +åˆå›žèµ·å‹•時ã«ã¯ã€æœ€åˆã® `online` (当ã¦ã¯ã¾ã‚‹å ´åˆ) イベントãŒå°‘ãªãã¨ã‚‚ç«ã‚’å‰ã«ç¬¬ 2 `connection.type` ã¯`UNKNOWN`. + +### Windows Phone 7 ã®ç™– + +エミュレーターã§å®Ÿè¡Œã—ã¦ã„ã‚‹ã¨ã〠`connection.status` ã¯å¸¸ã«çŸ¥ã‚‰ã‚Œã¦ã„ã‚‹ã€ã“ã®ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ + +### Windows Phone 8 ç™– + +ã‚¨ãƒŸãƒ¥ãƒ¬ãƒ¼ã‚¿ãƒ¼ã¨æŽ¥ç¶šã®ç¨®é¡žã®ãƒ¬ãƒãƒ¼ãƒˆ `Cellular` ã¯å¤‰åŒ–ã—ã¾ã›ã‚“ã€ã‚¤ãƒ™ãƒ³ãƒˆã¯*ãªã„*ç«ã€‚ diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/ko/README.md new file mode 100644 index 00000000..a6675391 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/ko/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +ì´ í”ŒëŸ¬ê·¸ì¸ [ë„¤íŠ¸ì›Œí¬ ì •ë³´ API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)ì˜ ì´ì „ ë²„ì „ì— ëŒ€ 한 êµ¬í˜„ì„ ì œê³µí•©ë‹ˆë‹¤. 소ìžì˜ 셀룰러와 와ì´íŒŒì´ ì—°ê²°ì— ëŒ€ 한 ì •ë³´ë¥¼ ì œê³µ 합니다 장치는 ì¸í„°ë„· ì—°ê²°ì— ìžˆëŠ”ì§€ 여부. + +## 설치 + + cordova plugin add cordova-plugin-network-information + + +## ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * 브ë¼ìš°ì € + * iOS + * Windows Phone 7ê³¼ 8 + * Tizen + * 윈ë„ìš° + * Firefox ìš´ì˜ ì²´ì œ + +# ì—°ê²° + +> `connection`개체를 통해 노출 `navigator.connection` , 소ìžì˜ 셀룰러와 와ì´íŒŒì´ ì—°ê²°ì— ëŒ€ 한 ì •ë³´ë¥¼ ì œê³µ 합니다. + +## ì†ì„± + + * connection.type + +## ìƒìˆ˜ + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +ì´ ë””ë°”ì´ìŠ¤ì˜ ë„¤íŠ¸ì›Œí¬ ì—°ê²° ìƒíƒœë¥¼ í™•ì¸ í•˜ëŠ” ë¹ ë¥¸ ë°©ë²•ì„ ì œê³µ 합니다 ë° ì—°ê²°ì˜ ì¢…ë¥˜. + +### ë¹ ë¥¸ ì˜ˆì œ + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 변경 + +코르 ë„ìš° ë°” 2.3.0까지 `Connection` 개체를 통해 액세스 했습니다 `navigator.network.connection` , í›„ì— ë³€ê²½ ëœ `navigator.connection` W3C ì‚¬ì–‘ì— ë§žê²Œ. ê·¸ê²ƒì€ ê·¸ê²ƒì˜ ì›ëž˜ ìœ„ì¹˜ì— ê³„ì† ì‚¬ìš©í• ìˆ˜ 하지만 사용 ë˜ì§€ 않습니다 ë° ê²°êµ ì œê±° ë 것 ì´ë‹¤. + +### iOS 단ì + + * iOS는 셀룰러 ë„¤íŠ¸ì›Œí¬ ì—°ê²°ì˜ ì¢…ë¥˜ë¥¼ ê°ì§€í• 수 없습니다. + * `navigator.connection.type`로 ì„¤ì • ëœ `Connection.CELL` ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한. + +### Windows Phone 단ì + + * ì—ë®¬ë ˆì´í„°ì—서 ì‹¤í–‰í• ë•Œ í•ìƒ ê²€ìƒ‰ `navigator.connection.type` 으로`Connection.UNKNOWN`. + + * Windows Phone 셀룰러 ë„¤íŠ¸ì›Œí¬ ì—°ê²° ìœ í˜•ì„ ê²€ìƒ‰í• ìˆ˜ 없습니다. + + * `navigator.connection.type`로 ì„¤ì • ëœ `Connection.CELL` ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한. + +### 윈ë„ìš° 특수 + + * ì „í™” 8.1 ì—ë®¬ë ˆì´í„°ì—서 실행 하는 경우 í•ìƒ `Connection.ETHERNET`로 `navigator.connection.type`를 ê°ì§€í•©ë‹ˆë‹¤. + +### Tizen 특수 + + * Tizenì€ ì™€ì´íŒŒì´ ë˜ëŠ” 휴대 ì „í™” ì—°ê²°ì—ë§Œ ê²€ìƒ‰í• ìˆ˜ 있습니다. + * `navigator.connection.type`는 ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한 `Connection.CELL_2G`로 ì„¤ì • ë©ë‹ˆë‹¤. + +### 파ì´ì–´ í스 OS 단ì + + * 파ì´ì–´ í스 OS 셀룰러 ë„¤íŠ¸ì›Œí¬ ì—°ê²° ìœ í˜•ì„ ê²€ìƒ‰í• ìˆ˜ 없습니다. + * `navigator.connection.type`로 ì„¤ì • ëœ `Connection.CELL` ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한. + +### 브ë¼ìš°ì € 만지면 + + * 브ë¼ìš°ì €ëŠ” ë„¤íŠ¸ì›Œí¬ ì—°ê²°ì˜ ì¢…ë¥˜ë¥¼ ê²€ìƒ‰í• ìˆ˜ 없습니다. `navigator.connection.type` `Connection.UNKNOWN` 때 온ë¼ì¸ìœ¼ë¡œ í•ìƒ ì„¤ì • ë©ë‹ˆë‹¤. + +# ë„¤íŠ¸ì›Œí¬ ê´€ë ¨ ì´ë²¤íЏ + +## offline + +ì´ë²¤íŠ¸ê°€ ë°œìƒ í•˜ë©´ ì‘ìš© 프로그램 오프 ë¼ì¸, ì´ë™ ë° ìž¥ì¹˜ê°€ ì¸í„°ë„·ì— ì—°ê²° ë˜ì–´ 있지. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 세부 ì •ë³´ + +`offline`ì´ë²¤íŠ¸ê°€ ë°œìƒ í•˜ë©´ ì‘ìš© í”„ë¡œê·¸ëž¨ì´ ë” ì´ìƒ ì¸í„°ë„·ì— ì•¡ì„¸ìŠ¤í• ìˆ˜ 있ë„ë¡ ì´ì „ ì—°ê²° ëœ ìž¥ì¹˜ê°€ ë„¤íŠ¸ì›Œí¬ ì—°ê²° ì†ì‹¤. ê·¸ê²ƒì€ ì—°ê²° API와 ë™ì¼í•œ ì •ë³´ì— ì˜ì¡´ 하 ê³ ê²½ìš°ì˜ ê°’ `connection.type` ëœë‹¤`NONE`. + +ì¼ë°˜ì 으로 ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì‚¬ìš© 해야 합니다 `document.addEventListener` 한번 ì´ë²¤íЏ 리스너를 ì—°ê²° 하는 `deviceready` ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. + +### ë¹ ë¥¸ ì˜ˆì œ + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 단ì + +ì²˜ìŒ ì‹œìž‘ 하는 ë™ì•ˆ 첫 번째 오프 ë¼ì¸ ì´ë²¤íЏ (있는 경우)를 ì ì–´ë„ ì´ˆë¥¼ 걸립니다. + +### Windows Phone 7 단ì + +ì—ë®¬ë ˆì´í„°ì—서 실행 하는 경우는 `connection.status` í•ìƒ ë¶ˆëª… 하다, ê·¸ëž˜ì„œì´ ì´ë²¤íŠ¸ëŠ” *없는* 불. + +### Windows Phone 8 단ì + +ì—ë®¬ë ˆì´í„°ë„ ì—°ê²° 형ì‹ì„ ë³´ê³ `Cellular` 는 변경 ë˜ì§€ 않습니다, 그래서 ì´ë²¤íЏ 않습니다 *하지* 불. + +## online + +ì‘ìš© í”„ë¡œê·¸ëž¨ì€ ì˜¨ë¼ì¸ ë° ìž¥ì¹˜ê°€ ì¸í„°ë„·ì— ì—°ê²° ëœë‹¤ ë•Œì´ ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. + + document.addEventListener("online", yourCallbackFunction, false); + + +### 세부 ì •ë³´ + +`online`ì´ì „ ì—°ê²° ë˜ì§€ ì•Šì€ ìž¥ì¹˜ëŠ” ì¸í„°ë„·ì— 대 한 ì‘ìš© 프로그램 액세스를 허용 하ë„ë¡ ë„¤íŠ¸ì›Œí¬ ì—°ê²°ì„ ë°›ì„ ë•Œ ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. ê·¸ê²ƒì€ ì—°ê²° API와 ë™ì¼í•œ ì •ë³´ì— ì˜ì¡´ 하 ê³ ê²½ìš°ì— `connection.type` ì—서 변경 `NONE` 다른 값으로. + +ì¼ë°˜ì 으로 ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì‚¬ìš© 해야 합니다 `document.addEventListener` 한번 ì´ë²¤íЏ 리스너를 ì—°ê²° 하는 `deviceready` ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. + +### ë¹ ë¥¸ ì˜ˆì œ + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 단ì + +ì²˜ìŒ ì‹œìž‘ 하는 ë™ì•ˆ 첫 번째 `online` ì´ë²¤íЏ (있는 경우) ì´ì „ì— ë¶ˆ ì´ˆ 걸립니다 ì´ìƒ `connection.type` 입니다`UNKNOWN`. + +### Windows Phone 7 단ì + +ì—ë®¬ë ˆì´í„°ì—서 실행 하는 경우는 `connection.status` í•ìƒ ë¶ˆëª… 하다, ê·¸ëž˜ì„œì´ ì´ë²¤íŠ¸ëŠ” *없는* 불. + +### Windows Phone 8 단ì + +ì—ë®¬ë ˆì´í„°ë„ ì—°ê²° 형ì‹ì„ ë³´ê³ `Cellular` 는 변경 ë˜ì§€ 않습니다, 그래서 ì´ë²¤íЏ 않습니다 *하지* 불.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/ko/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/ko/index.md new file mode 100644 index 00000000..cb4c727a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/ko/index.md @@ -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. +--> + +# cordova-plugin-network-information + +ì´ í”ŒëŸ¬ê·¸ì¸ [ë„¤íŠ¸ì›Œí¬ ì •ë³´ API][1]ì˜ ì´ì „ ë²„ì „ì— ëŒ€ 한 êµ¬í˜„ì„ ì œê³µí•©ë‹ˆë‹¤. 소ìžì˜ 셀룰러와 와ì´íŒŒì´ ì—°ê²°ì— ëŒ€ 한 ì •ë³´ë¥¼ ì œê³µ 합니다 장치는 ì¸í„°ë„· ì—°ê²°ì— ìžˆëŠ”ì§€ 여부. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## 설치 + + cordova plugin add cordova-plugin-network-information + + +## ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* 브ë¼ìš°ì € +* iOS +* Windows Phone 7ê³¼ 8 +* Tizen +* 윈ë„ìš° +* Firefox ìš´ì˜ ì²´ì œ + +# ì—°ê²° + +> `connection`개체를 통해 노출 `navigator.connection` , 소ìžì˜ 셀룰러와 와ì´íŒŒì´ ì—°ê²°ì— ëŒ€ 한 ì •ë³´ë¥¼ ì œê³µ 합니다. + +## ì†ì„± + +* connection.type + +## ìƒìˆ˜ + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +ì´ ë””ë°”ì´ìŠ¤ì˜ ë„¤íŠ¸ì›Œí¬ ì—°ê²° ìƒíƒœë¥¼ í™•ì¸ í•˜ëŠ” ë¹ ë¥¸ ë°©ë²•ì„ ì œê³µ 합니다 ë° ì—°ê²°ì˜ ì¢…ë¥˜. + +### ë¹ ë¥¸ ì˜ˆì œ + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 변경 + +코르 ë„ìš° ë°” 2.3.0까지 `Connection` 개체를 통해 액세스 했습니다 `navigator.network.connection` , í›„ì— ë³€ê²½ ëœ `navigator.connection` W3C ì‚¬ì–‘ì— ë§žê²Œ. ê·¸ê²ƒì€ ê·¸ê²ƒì˜ ì›ëž˜ ìœ„ì¹˜ì— ê³„ì† ì‚¬ìš©í• ìˆ˜ 하지만 사용 ë˜ì§€ 않습니다 ë° ê²°êµ ì œê±° ë 것 ì´ë‹¤. + +### iOS 단ì + +* iOS는 셀룰러 ë„¤íŠ¸ì›Œí¬ ì—°ê²°ì˜ ì¢…ë¥˜ë¥¼ ê°ì§€í• 수 없습니다. + * `navigator.connection.type`로 ì„¤ì • ëœ `Connection.CELL` ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한. + +### Windows Phone 단ì + +* ì—ë®¬ë ˆì´í„°ì—서 ì‹¤í–‰í• ë•Œ í•ìƒ ê²€ìƒ‰ `navigator.connection.type` 으로`Connection.UNKNOWN`. + +* Windows Phone 셀룰러 ë„¤íŠ¸ì›Œí¬ ì—°ê²° ìœ í˜•ì„ ê²€ìƒ‰í• ìˆ˜ 없습니다. + + * `navigator.connection.type`로 ì„¤ì • ëœ `Connection.CELL` ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한. + +### 윈ë„ìš° 특수 + +* ì „í™” 8.1 ì—ë®¬ë ˆì´í„°ì—서 실행 하는 경우 í•ìƒ `Connection.ETHERNET`로 `navigator.connection.type`를 ê°ì§€í•©ë‹ˆë‹¤. + +### Tizen 특수 + +* Tizenì€ ì™€ì´íŒŒì´ ë˜ëŠ” 휴대 ì „í™” ì—°ê²°ì—ë§Œ ê²€ìƒ‰í• ìˆ˜ 있습니다. + * `navigator.connection.type`는 ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한 `Connection.CELL_2G`로 ì„¤ì • ë©ë‹ˆë‹¤. + +### 파ì´ì–´ í스 OS 단ì + +* 파ì´ì–´ í스 OS 셀룰러 ë„¤íŠ¸ì›Œí¬ ì—°ê²° ìœ í˜•ì„ ê²€ìƒ‰í• ìˆ˜ 없습니다. + * `navigator.connection.type`로 ì„¤ì • ëœ `Connection.CELL` ëª¨ë“ ì…€ë£°ëŸ¬ ë°ì´í„°ì— 대 한. + +# ë„¤íŠ¸ì›Œí¬ ê´€ë ¨ ì´ë²¤íЏ + +## offline + +ì´ë²¤íŠ¸ê°€ ë°œìƒ í•˜ë©´ ì‘ìš© 프로그램 오프 ë¼ì¸, ì´ë™ ë° ìž¥ì¹˜ê°€ ì¸í„°ë„·ì— ì—°ê²° ë˜ì–´ 있지. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 세부 ì •ë³´ + +`offline`ì´ë²¤íŠ¸ê°€ ë°œìƒ í•˜ë©´ ì‘ìš© í”„ë¡œê·¸ëž¨ì´ ë” ì´ìƒ ì¸í„°ë„·ì— ì•¡ì„¸ìŠ¤í• ìˆ˜ 있ë„ë¡ ì´ì „ ì—°ê²° ëœ ìž¥ì¹˜ê°€ ë„¤íŠ¸ì›Œí¬ ì—°ê²° ì†ì‹¤. ê·¸ê²ƒì€ ì—°ê²° API와 ë™ì¼í•œ ì •ë³´ì— ì˜ì¡´ 하 ê³ ê²½ìš°ì˜ ê°’ `connection.type` ëœë‹¤`NONE`. + +ì¼ë°˜ì 으로 ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì‚¬ìš© 해야 합니다 `document.addEventListener` 한번 ì´ë²¤íЏ 리스너를 ì—°ê²° 하는 `deviceready` ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. + +### ë¹ ë¥¸ ì˜ˆì œ + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 단ì + +ì²˜ìŒ ì‹œìž‘ 하는 ë™ì•ˆ 첫 번째 오프 ë¼ì¸ ì´ë²¤íЏ (있는 경우)를 ì ì–´ë„ ì´ˆë¥¼ 걸립니다. + +### Windows Phone 7 단ì + +ì—ë®¬ë ˆì´í„°ì—서 실행 하는 경우는 `connection.status` í•ìƒ ë¶ˆëª… 하다, ê·¸ëž˜ì„œì´ ì´ë²¤íŠ¸ëŠ” *없는* 불. + +### Windows Phone 8 단ì + +ì—ë®¬ë ˆì´í„°ë„ ì—°ê²° 형ì‹ì„ ë³´ê³ `Cellular` 는 변경 ë˜ì§€ 않습니다, 그래서 ì´ë²¤íЏ 않습니다 *하지* 불. + +## online + +ì‘ìš© í”„ë¡œê·¸ëž¨ì€ ì˜¨ë¼ì¸ ë° ìž¥ì¹˜ê°€ ì¸í„°ë„·ì— ì—°ê²° ëœë‹¤ ë•Œì´ ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. + + document.addEventListener("online", yourCallbackFunction, false); + + +### 세부 ì •ë³´ + +`online`ì´ì „ ì—°ê²° ë˜ì§€ ì•Šì€ ìž¥ì¹˜ëŠ” ì¸í„°ë„·ì— 대 한 ì‘ìš© 프로그램 액세스를 허용 하ë„ë¡ ë„¤íŠ¸ì›Œí¬ ì—°ê²°ì„ ë°›ì„ ë•Œ ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. ê·¸ê²ƒì€ ì—°ê²° API와 ë™ì¼í•œ ì •ë³´ì— ì˜ì¡´ 하 ê³ ê²½ìš°ì— `connection.type` ì—서 변경 `NONE` 다른 값으로. + +ì¼ë°˜ì 으로 ì‘ìš© í”„ë¡œê·¸ëž¨ì„ ì‚¬ìš© 해야 합니다 `document.addEventListener` 한번 ì´ë²¤íЏ 리스너를 ì—°ê²° 하는 `deviceready` ì´ë²¤íŠ¸ê°€ ë°œìƒ í•©ë‹ˆë‹¤. + +### ë¹ ë¥¸ ì˜ˆì œ + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 단ì + +ì²˜ìŒ ì‹œìž‘ 하는 ë™ì•ˆ 첫 번째 `online` ì´ë²¤íЏ (있는 경우) ì´ì „ì— ë¶ˆ ì´ˆ 걸립니다 ì´ìƒ `connection.type` 입니다`UNKNOWN`. + +### Windows Phone 7 단ì + +ì—ë®¬ë ˆì´í„°ì—서 실행 하는 경우는 `connection.status` í•ìƒ ë¶ˆëª… 하다, ê·¸ëž˜ì„œì´ ì´ë²¤íŠ¸ëŠ” *없는* 불. + +### Windows Phone 8 단ì + +ì—ë®¬ë ˆì´í„°ë„ ì—°ê²° 형ì‹ì„ ë³´ê³ `Cellular` 는 변경 ë˜ì§€ 않습니다, 그래서 ì´ë²¤íЏ 않습니다 *하지* 불. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/pl/README.md new file mode 100644 index 00000000..4b66cbb4 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/pl/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +Wtyczka stanowi implementacjÄ™ starÄ… wersjÄ™ [API informacji w sieci](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). UdostÄ™pnia informacje na temat urzÄ…dzenia komórkowe i wifi połączenie, i czy urzÄ…dzenie ma połączenie z Internetem. + +## Instalacja + + cordova plugin add cordova-plugin-network-information + + +## ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * PrzeglÄ…darka + * iOS + * Windows Phone 7 i 8 + * Tizen + * Windows + * Firefox OS + +# Połączenie + +> `connection`Obiektu, wystawiony przez `navigator.connection` , zawiera informacje o połączeniu urzÄ…dzenia komórkowe i wifi. + +## WÅ‚aÅ›ciwoÅ›ci + + * Connection.Type + +## StaÅ‚e + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## Connection.Type + +Oferuje szybki sposób ustalić stan połączenia sieciowego urzÄ…dzenia i typ połączenia. + +### Szybki przykÅ‚ad + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Zmiana interfejsu API + +Do Cordova 2.3.0 `Connection` obiekt uzyskano za poÅ›rednictwem `navigator.network.connection` , po którym zostaÅ‚ zmieniony na `navigator.connection` odpowiadać specyfikacji W3C. To jest nadal dostÄ™pne w jego oryginalnej lokalizacji, ale jest niezalecane i zostanÄ… ostatecznie usuniÄ™te. + +### Dziwactwa iOS + + * iOS nie może wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows Phone dziwactwa + + * Po uruchomieniu w emulatorze, zawsze wykrywa `navigator.connection.type` jako`Connection.UNKNOWN`. + + * Windows Phone nie może wykryć typ połączenia w sieci komórkowej. + + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows dziwactwa + + * Po uruchomieniu w emulatorze telefonu 8.1, zawsze wykrywa `navigator.connection.type` jako `Connection.ETHERNET`. + +### Dziwactwa Tizen + + * Tizen można tylko dostrzegać Wi-Fi lub połączenia komórkowe. + * `Navigator.Connection.Type` jest zestaw do `Connection.CELL_2G` dla wszystkich komórek danych. + +### Firefox OS dziwactwa + + * Firefox OS nie można wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Quirks przeglÄ…darki + + * PrzeglÄ…darka nie może wykryć typ połączenia sieciowego. `Navigator.Connection.Type` jest zawsze zestaw do `Connection.UNKNOWN` podczas online. + +# Zdarzenia zwiÄ…zane z sieci + +## offline + +Zdarzenie odpala gdy aplikacja przejdzie do trybu offline, a urzÄ…dzenie nie jest podłączone do Internetu. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Szczegóły + +`offline`Zdarzenie fires po wczeÅ›niej podłączone urzÄ…dzenie traci połączenia z sieciÄ…, dziÄ™ki czemu aplikacja może już dostÄ™p do Internetu. Opiera siÄ™ na te same informacje połączenia API i gdy odpalam wartość `connection.type` staje siÄ™`NONE`. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć sÅ‚uchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykÅ‚ad + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwsza impreza offline (jeÅ›li dotyczy) trwa co najmniej drugi ognia. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, wiÄ™c to wydarzenie *nie* ogieÅ„. + +### Windows Phone 8 dziwactwa + +Emulator raporty typ połączenia, jako `Cellular` , co nie zmienia, wiÄ™c zdarzenie *nie* ogieÅ„. + +## online + +Wydarzenie to odpala gdy aplikacja przechodzi w tryb online i urzÄ…dzenie staje siÄ™ połączenie z Internetem. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Szczegóły + +`online`Zdarzenie odpala gdy wczeÅ›niej niezwiÄ…zane urzÄ…dzenie odbiera połączenie sieciowe, aby umożliwić aplikacji dostÄ™p do Internetu. Opiera siÄ™ na te same informacje połączenia API i gdy odpalam `connection.type` zmienia siÄ™ z `NONE` na innÄ… wartość. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć sÅ‚uchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykÅ‚ad + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwszy `online` zdarzenia (w stosownych przypadkach) zajmuje co najmniej drugie ognia, przed którym `connection.type` jest`UNKNOWN`. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, wiÄ™c to wydarzenie *nie* ogieÅ„. + +### Windows Phone 8 dziwactwa + +Emulator sprawozdania jako typ połączenia `Cellular` , które nie zmienia, wiÄ™c wydarzenia czy *nie* ogieÅ„.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/pl/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/pl/index.md new file mode 100644 index 00000000..a42b973c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/pl/index.md @@ -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. +--> + +# cordova-plugin-network-information + +Wtyczka stanowi implementacjÄ™ starÄ… wersjÄ™ [API informacji w sieci][1]. UdostÄ™pnia informacje na temat urzÄ…dzenia komórkowe i wifi połączenie, i czy urzÄ…dzenie ma połączenie z Internetem. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Instalacja + + cordova plugin add cordova-plugin-network-information + + +## ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* PrzeglÄ…darka +* iOS +* Windows Phone 7 i 8 +* Tizen +* Windows +* Firefox OS + +# Połączenie + +> `connection`Obiektu, wystawiony przez `navigator.connection` , zawiera informacje o połączeniu urzÄ…dzenia komórkowe i wifi. + +## WÅ‚aÅ›ciwoÅ›ci + +* Connection.Type + +## StaÅ‚e + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## Connection.Type + +Oferuje szybki sposób ustalić stan połączenia sieciowego urzÄ…dzenia i typ połączenia. + +### Szybki przykÅ‚ad + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Zmiana interfejsu API + +Do Cordova 2.3.0 `Connection` obiekt uzyskano za poÅ›rednictwem `navigator.network.connection` , po którym zostaÅ‚ zmieniony na `navigator.connection` odpowiadać specyfikacji W3C. To jest nadal dostÄ™pne w jego oryginalnej lokalizacji, ale jest niezalecane i zostanÄ… ostatecznie usuniÄ™te. + +### Dziwactwa iOS + +* iOS nie może wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows Phone dziwactwa + +* Po uruchomieniu w emulatorze, zawsze wykrywa `navigator.connection.type` jako`Connection.UNKNOWN`. + +* Windows Phone nie może wykryć typ połączenia w sieci komórkowej. + + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows dziwactwa + +* Po uruchomieniu w emulatorze telefonu 8.1, zawsze wykrywa `navigator.connection.type` jako `Connection.ETHERNET`. + +### Dziwactwa Tizen + +* Tizen można tylko dostrzegać Wi-Fi lub połączenia komórkowe. + * `Navigator.Connection.Type` jest zestaw do `Connection.CELL_2G` dla wszystkich komórek danych. + +### Firefox OS dziwactwa + +* Firefox OS nie można wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +# Zdarzenia zwiÄ…zane z sieci + +## offline + +Zdarzenie odpala gdy aplikacja przejdzie do trybu offline, a urzÄ…dzenie nie jest podłączone do Internetu. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Szczegóły + +`offline`Zdarzenie fires po wczeÅ›niej podłączone urzÄ…dzenie traci połączenia z sieciÄ…, dziÄ™ki czemu aplikacja może już dostÄ™p do Internetu. Opiera siÄ™ na te same informacje połączenia API i gdy odpalam wartość `connection.type` staje siÄ™`NONE`. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć sÅ‚uchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykÅ‚ad + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwsza impreza offline (jeÅ›li dotyczy) trwa co najmniej drugi ognia. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, wiÄ™c to wydarzenie *nie* ogieÅ„. + +### Windows Phone 8 dziwactwa + +Emulator raporty typ połączenia, jako `Cellular` , co nie zmienia, wiÄ™c zdarzenie *nie* ogieÅ„. + +## online + +Wydarzenie to odpala gdy aplikacja przechodzi w tryb online i urzÄ…dzenie staje siÄ™ połączenie z Internetem. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Szczegóły + +`online`Zdarzenie odpala gdy wczeÅ›niej niezwiÄ…zane urzÄ…dzenie odbiera połączenie sieciowe, aby umożliwić aplikacji dostÄ™p do Internetu. Opiera siÄ™ na te same informacje połączenia API i gdy odpalam `connection.type` zmienia siÄ™ z `NONE` na innÄ… wartość. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć sÅ‚uchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykÅ‚ad + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwszy `online` zdarzenia (w stosownych przypadkach) zajmuje co najmniej drugie ognia, przed którym `connection.type` jest`UNKNOWN`. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, wiÄ™c to wydarzenie *nie* ogieÅ„. + +### Windows Phone 8 dziwactwa + +Emulator sprawozdania jako typ połączenia `Cellular` , które nie zmienia, wiÄ™c wydarzenia czy *nie* ogieÅ„. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/ru/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/ru/index.md new file mode 100644 index 00000000..481c1b18 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/ru/index.md @@ -0,0 +1,182 @@ +<!--- + 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-plugin-network-information + +Ðтот плагин обеÑпечивает реализацию Ñтарой верÑии [API Сетевой информации][1]. Он предоÑтавлÑет информацию о Ñотовых и Wi-Fi подключениÑÑ… уÑтройÑтва, и информацию имеет ли уÑтройÑтво подключение к Интернету. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## УÑтановка + + cordova plugin add cordova-plugin-network-information + + +## Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Браузер +* iOS +* Windows Phone 7 и 8 +* Tizen +* Windows 8 +* Firefox OS + +# Connection + +> Объект `connection`, доÑтупный через `navigator.connection`, предоÑтавлÑет информацию о Ñотовых и wifi подключениÑÑ… уÑтройÑтва. + +## СвойÑтва + +* connection.type + +## КонÑтанты + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Ðто ÑвойÑтво предоÑтавлÑет быÑтрый ÑпоÑоб Ð´Ð»Ñ Ð¾Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ ÑоÑтоÑÐ½Ð¸Ñ Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ ÑƒÑтройÑтва к Ñети и тип Ñтого подключениÑ. + +### Краткий пример + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Ð˜Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð² API + +До Cordova 2.3.0 объект `Connection` был доÑтупен через `navigator.network.connection`, поÑле чего Ñто ÑвойÑтво было изменено на `navigator.connection` в ÑоответÑтвии Ñо Ñпецификацией конÑорциума W3C. Он вÑе еще доÑтупен в его иÑходном раÑположении, но Ñто раÑположение ÑвлÑетÑÑ ÑƒÑтаревшим и в конечном итоге будет удалено. + +### ОÑобенноÑти iOS + +* iOS не может определить тип Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ðº Ñотовой Ñети. + * `navigator.connection.type` имеет значение `Connection.CELL` Ð´Ð»Ñ Ð²Ñех Ñотовых данных. + +### ОÑобенноÑти Windows Phone + +* Когда работает в ÑмулÑторе, тип Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ð²Ñегда определÑетÑÑ `navigator.connection.type` как `Connection.UNKNOWN`. + +* Windows Phone не может определить тип Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ðº Ñотовой Ñети. + + * `navigator.connection.type` имеет значение `Connection.CELL` Ð´Ð»Ñ Ð²Ñех Ñотовых данных. + +### ОÑобенноÑти Tizen + +* Tizen может обнаружить только ÑÐ¾ÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ Wi-Fi или наличие Ñотовой ÑвÑзи. + * `navigator.connection.type` имеет значение `Connection.CELL_2G` Ð´Ð»Ñ Ð²Ñех Ñотовых данных. + +### ОÑобенноÑти Firefox OS + +* Firefox OS не может определить тип Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ðº Ñотовой Ñети. + * `navigator.connection.type` имеет значение `Connection.CELL` Ð´Ð»Ñ Ð²Ñех Ñотовых данных. + +# СобытиÑ, ÑвÑзанные Ñ Ñетью + +## offline + +Событие возникает, когда приложение переходит в автономный режим, и уÑтройÑтво не подключено к Ñети Интернет. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### ПодробноÑти + +Событие `offline` возникает, когда ранее подключенное уÑтройÑтво терÑет подключение к Ñети, так что приложение больше не может получить доÑтуп к Интернет. Он опираетÑÑ Ð½Ð° ту же информацию, что и Connection API и Ñрабатывает, когда значение `connection.type` ÑтановитÑÑ Ñ€Ð°Ð²Ð½Ñ‹Ð¼ `NONE`. + +ÐŸÑ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ‹Ñ‡Ð½Ð¾ должно иÑпользовать `window.addEventListener` чтобы добавить обработчик ÑÐ¾Ð±Ñ‹Ñ‚Ð¸Ñ Ð¿Ð¾Ñле того как произойдет Ñобытие `deviceready`. + +### Краткий пример + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### ОÑобенноÑти iOS + +Во Ð²Ñ€ÐµÐ¼Ñ Ð¿ÐµÑ€Ð²Ð¾Ð½Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ запуÑка первому Ñобытию offline (еÑли применимо) требуетÑÑ Ð¿Ð¾ крайней мере Ñекунду на Ñрабатывание. + +### ОÑобенноÑти Windows Phone 7 + +Когда работает в ÑмулÑторе, `connection.status` вÑегда неизвеÑтен, так что Ñто Ñобытие *не* Ñрабатывает. + +### ОÑобенноÑти Windows Phone 8 + +ÐмулÑтор Ñообщает тип Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ ÐºÐ°Ðº `Cellular` , которое не менÑетÑÑ, поÑтому Ñобытие не *не* Ñрабатывает. + +## online + +Ðто Ñобытие возникает, когда приложение выходит в онлайн, и уÑтройÑтво подключаетÑÑ Ðº Интернету. + + document.addEventListener("online", yourCallbackFunction, false); + + +### ПодробноÑти + +Событие `online` возникает, когда ранее не подключенное к Ñети уÑтройÑтво получает Ñетевое подключение, разрешающее приложению доÑтуп к Интернету. Оно опираетÑÑ Ð½Ð° ту же информацию, Connection API и вызываетÑÑ ÐºÐ¾Ð³Ð´Ð° `connection.type` менÑетÑÑ Ñ `NONE` в любое другое значение. + +ÐŸÑ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ‹Ñ‡Ð½Ð¾ должны иÑпользовать `window.addEventListener` чтобы добавить обработчик ÑÐ¾Ð±Ñ‹Ñ‚Ð¸Ñ Ð¿Ð¾Ñле того как произойдет Ñобытие `deviceready`. + +### Краткий пример + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### ОÑобенноÑти iOS + +Во Ð²Ñ€ÐµÐ¼Ñ Ð¿ÐµÑ€Ð²Ð¾Ð½Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ запуÑка первое Ñобытие `online` (еÑли применимо) занимает по меньшей мере Ñекунду на Ñрабатывание, до Ñтого момента `connection.type` ÑвлÑетÑÑ Ñ€Ð°Ð²Ð½Ñ‹Ð¼ `UNKNOWN`. + +### ОÑобенноÑти Windows Phone 7 + +Когда работает в ÑмулÑторе, `connection.status` вÑегда неизвеÑтен, так что Ñто Ñобытие *не* Ñрабатывает. + +### ОÑобенноÑти Windows Phone 8 + +ÐмулÑтор Ñообщает тип Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ ÐºÐ°Ðº `Cellular` , которое не менÑетÑÑ, поÑтому Ñобытие не *не* Ñрабатывает. diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/zh/README.md new file mode 100644 index 00000000..09e11e7e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/zh/README.md @@ -0,0 +1,190 @@ +<!-- +# license: 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-plugin-network-information + +[](https://travis-ci.org/apache/cordova-plugin-network-information) + +é€™å€‹å¤–æŽ›ç¨‹å¼æä¾›çš„èˆŠç‰ˆæœ¬çš„[網路資訊 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)實ç¾çš„。 它æä¾›äº†æœ‰é—œè©²è¨å‚™çš„行動電話和無線網路連接的資訊和è¨å‚™æ˜¯å¦å·²é€£æŽ¥åˆ° internet。 + +## å®‰è£ + + cordova plugin add cordova-plugin-network-information + + +## 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * ç€è¦½å™¨ + * iOS + * Windows Phone 7 å’Œ 8 + * Tizen + * Windows + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ± + +# 連接 + +> `connection`物件,通éŽå…¬é–‹ `navigator.connection` ,æä¾›äº†æœ‰é—œè©²è¨å‚™çš„行動電話和無線網路連接的資訊。 + +## 屬性 + + * connection.type + +## å¸¸é‡ + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +æ¤å±¬æ€§æä¾›å¿«é€Ÿçš„æ–¹æ³•來確定è¨å‚™çš„網路連接狀態,和連線類型。 + +### 快速的示例 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 更改 + +科爾多瓦 2.3.0,直到 `Connection` 物件的訪å•é€šéŽ `navigator.network.connection` å¾Œæ‰æ”¹ç‚ºå…¶ä¸, `navigator.connection` 以匹é…çš„ W3C è¦ç¯„。 它在其原始ä½ç½®ï¼Œæ˜¯ä»ç„¶å¯ç”¨ï¼Œä½†å·²å»¢æ£„,最終將被刪除。 + +### iOS 的怪癖 + + * iOS 無法檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`è¨ç½®ç‚º `Connection.CELL` 為所有蜂窩資料。 + +### Windows Phone 怪癖 + + * ç•¶é‹è¡Œåœ¨æ¨¡æ“¬å™¨ä¸ï¼Œç¸½èƒ½æª¢æ¸¬åˆ° `navigator.connection.type` 作為`Connection.UNKNOWN`. + + * Windows Phone ä¸èƒ½æª¢æ¸¬çš„蜂窩網路連接的類型。 + + * `navigator.connection.type`è¨ç½®ç‚º `Connection.CELL` 為所有蜂窩資料。 + +### Windows 的怪癖 + + * 當電話 8.1 在模擬器ä¸é‹è¡Œï¼Œç¸½èƒ½æª¢æ¸¬åˆ° `navigator.connection.type` 作為 `Connection.ETHERNET`. + +### Tizen 怪癖 + + * æ³°åªèƒ½æª¢æ¸¬ä¸€å€‹ WiFi 或細胞連接。 + * `navigator.connection.type` 是所有蜂窩資料è¨ç½®ç‚º `Connection.CELL_2G`。 + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±çš„æ€ªç™– + + * ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±ç„¡æ³•檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`è¨ç½®ç‚º `Connection.CELL` 為所有蜂窩資料。 + +### ç€è¦½å™¨çš„æ€ªç™– + + * ç€è¦½å™¨ç„¡æ³•檢測到網路連接的類型。 `navigator.connection.type`總是被è¨ç½®ç‚º`Connection.UNKNOWN`時線上。 + +# 與網路相關的事件 + +## offline + +當一個應用程å¼é›¢ç·šæ™‚,與該è¨å‚™æœªé€£æŽ¥åˆ°äº’è¯ç¶²æ™‚,將觸發該事件。 + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細資訊 + +`offline`以å‰é€£æŽ¥çš„è¨å‚™å¤±åŽ»ç¶²è·¯é€£æŽ¥ï¼Œé€™æ¨£ï¼Œæ‡‰ç”¨ç¨‹å¼ä¸å†å¯ä»¥è¨ªå•互è¯ç¶²æ™‚激發的事件。 它ä¾è³´äºŽé€£æŽ¥ API,相åŒçš„資訊和ç«ç½æ™‚的值 `connection.type` 變得`NONE`. + +應用程å¼é€šå¸¸æ‡‰ä½¿ç”¨ `document.addEventListener` å°‡ä¸€å€‹äº‹ä»¶æ””æˆªå™¨é™„åŠ ä¸€æ¬¡ `deviceready` 事件ç«ç½ã€‚ + +### 快速的示例 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 的怪癖 + +在åˆå§‹å•Ÿå‹•期間,第一次離線事件 (如果é©ç”¨ï¼‰ 需至少一秒的ç«ã€‚ + +### Windows Phone 7 的怪癖 + +ç•¶é‹è¡Œåœ¨æ¨¡æ“¬å™¨ä¸ï¼Œ `connection.status` å§‹çµ‚æ˜¯æœªçŸ¥çš„å› æ¤æ¤äº‹ä»¶ä¸æœƒ*ä¸*ç«ã€‚ + +### Windows Phone 8 怪癖 + +模擬程å¼å ±å‘Šé€£ç·šé¡žåž‹ç‚º `Cellular` ï¼Œè€Œä¸æœƒæ›´æ”¹ï¼Œæ‰€ä»¥è©²äº‹ä»¶ä¸æœƒ*ä¸*ç«ã€‚ + +## online + +當應用程å¼é€²å…¥ç·šä¸Šç‹€æ…‹ï¼Œå’Œè©²è¨å‚™å°‡æˆç‚ºé€£æŽ¥åˆ°äº’è¯ç¶²æ™‚觸發æ¤äº‹ä»¶ã€‚ + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細資訊 + +`online`ç•¶å…ˆå‰é€£æŽ¥çš„行動è£ç½®æŽ¥æ”¶åˆ°ä¸€å€‹ç¶²è·¯é€£æŽ¥ä»¥å…許應用程å¼è¨ªå•互è¯ç¶²æ™‚激發的事件。 它ä¾è³´äºŽé€£æŽ¥ API,相åŒçš„資訊,則會激發 `connection.type` 從更改 `NONE` 為任何其他值。 + +應用程å¼é€šå¸¸æ‡‰ä½¿ç”¨ `document.addEventListener` å°‡ä¸€å€‹äº‹ä»¶æ””æˆªå™¨é™„åŠ ä¸€æ¬¡ `deviceready` 事件ç«ç½ã€‚ + +### 快速的示例 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 的怪癖 + +在åˆå§‹å•Ÿå‹•期間第一次 `online` 事件 (如果é©ç”¨ï¼‰ï¼Œè‡³å°‘需一秒的ç«ç½ä¹‹å‰çš„, `connection.type` 是`UNKNOWN`. + +### Windows Phone 7 的怪癖 + +ç•¶é‹è¡Œåœ¨æ¨¡æ“¬å™¨ä¸ï¼Œ `connection.status` å§‹çµ‚æ˜¯æœªçŸ¥çš„å› æ¤æ¤äº‹ä»¶ä¸æœƒ*ä¸*ç«ã€‚ + +### Windows Phone 8 怪癖 + +模擬程å¼å ±å‘Šé€£ç·šé¡žåž‹ç‚º `Cellular` ï¼Œè€Œä¸æœƒæ›´æ”¹ï¼Œæ‰€ä»¥äº‹ä»¶ä¸**ç«ã€‚
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-network-information/doc/zh/index.md b/StoneIsland/plugins/cordova-plugin-network-information/doc/zh/index.md new file mode 100644 index 00000000..2041467e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/doc/zh/index.md @@ -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. +--> + +# cordova-plugin-network-information + +é€™å€‹å¤–æŽ›ç¨‹å¼æä¾›çš„èˆŠç‰ˆæœ¬çš„[網路資訊 API][1]實ç¾çš„。 它æä¾›äº†æœ‰é—œè©²è¨å‚™çš„行動電話和無線網路連接的資訊和è¨å‚™æ˜¯å¦å·²é€£æŽ¥åˆ° internet。 + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## å®‰è£ + + cordova plugin add cordova-plugin-network-information + + +## 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* ç€è¦½å™¨ +* iOS +* Windows Phone 7 å’Œ 8 +* æ³° +* Windows +* ç«ç‹ç€è¦½å™¨çš„作æ¥ç³»çµ± + +# 連接 + +> `connection`物件,通éŽå…¬é–‹ `navigator.connection` ,æä¾›äº†æœ‰é—œè©²è¨å‚™çš„行動電話和無線網路連接的資訊。 + +## 屬性 + +* connection.type + +## å¸¸é‡ + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +æ¤å±¬æ€§æä¾›å¿«é€Ÿçš„æ–¹æ³•來確定è¨å‚™çš„網路連接狀態,和連線類型。 + +### 快速的示例 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 更改 + +科爾多瓦 2.3.0,直到 `Connection` 物件的訪å•é€šéŽ `navigator.network.connection` å¾Œæ‰æ”¹ç‚ºå…¶ä¸, `navigator.connection` 以匹é…çš„ W3C è¦ç¯„。 它在其原始ä½ç½®ï¼Œæ˜¯ä»ç„¶å¯ç”¨ï¼Œä½†å·²å»¢æ£„,最終將被刪除。 + +### iOS 的怪癖 + +* iOS 無法檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`è¨ç½®ç‚º `Connection.CELL` 為所有蜂窩資料。 + +### Windows Phone 怪癖 + +* ç•¶é‹è¡Œåœ¨æ¨¡æ“¬å™¨ä¸ï¼Œç¸½èƒ½æª¢æ¸¬åˆ° `navigator.connection.type` 作為`Connection.UNKNOWN`. + +* Windows Phone ä¸èƒ½æª¢æ¸¬çš„蜂窩網路連接的類型。 + + * `navigator.connection.type`è¨ç½®ç‚º `Connection.CELL` 為所有蜂窩資料。 + +### Windows 的怪癖 + +* 當電話 8.1 在模擬器ä¸é‹è¡Œï¼Œç¸½èƒ½æª¢æ¸¬åˆ° `navigator.connection.type` 作為 `Connection.ETHERNET`. + +### Tizen 怪癖 + +* æ³°åªèƒ½æª¢æ¸¬ä¸€å€‹ WiFi 或細胞連接。 + * `navigator.connection.type` 是所有蜂窩資料è¨ç½®ç‚º `Connection.CELL_2G`。 + +### ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±çš„æ€ªç™– + +* ç«ç‹ç€è¦½å™¨ä½œæ¥ç³»çµ±ç„¡æ³•檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`è¨ç½®ç‚º `Connection.CELL` 為所有蜂窩資料。 + +# 與網路相關的事件 + +## offline + +當一個應用程å¼é›¢ç·šæ™‚,與該è¨å‚™æœªé€£æŽ¥åˆ°äº’è¯ç¶²æ™‚,將觸發該事件。 + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細資訊 + +`offline`以å‰é€£æŽ¥çš„è¨å‚™å¤±åŽ»ç¶²è·¯é€£æŽ¥ï¼Œé€™æ¨£ï¼Œæ‡‰ç”¨ç¨‹å¼ä¸å†å¯ä»¥è¨ªå•互è¯ç¶²æ™‚激發的事件。 它ä¾è³´äºŽé€£æŽ¥ API,相åŒçš„資訊和ç«ç½æ™‚的值 `connection.type` 變得`NONE`. + +應用程å¼é€šå¸¸æ‡‰ä½¿ç”¨ `document.addEventListener` å°‡ä¸€å€‹äº‹ä»¶æ””æˆªå™¨é™„åŠ ä¸€æ¬¡ `deviceready` 事件ç«ç½ã€‚ + +### 快速的示例 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 的怪癖 + +在åˆå§‹å•Ÿå‹•期間,第一次離線事件 (如果é©ç”¨ï¼‰ 需至少一秒的ç«ã€‚ + +### Windows Phone 7 的怪癖 + +ç•¶é‹è¡Œåœ¨æ¨¡æ“¬å™¨ä¸ï¼Œ `connection.status` å§‹çµ‚æ˜¯æœªçŸ¥çš„å› æ¤æ¤äº‹ä»¶ä¸æœƒ*ä¸*ç«ã€‚ + +### Windows Phone 8 怪癖 + +模擬程å¼å ±å‘Šé€£ç·šé¡žåž‹ç‚º `Cellular` ï¼Œè€Œä¸æœƒæ›´æ”¹ï¼Œæ‰€ä»¥è©²äº‹ä»¶ä¸æœƒ*ä¸*ç«ã€‚ + +## online + +當應用程å¼é€²å…¥ç·šä¸Šç‹€æ…‹ï¼Œå’Œè©²è¨å‚™å°‡æˆç‚ºé€£æŽ¥åˆ°äº’è¯ç¶²æ™‚觸發æ¤äº‹ä»¶ã€‚ + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細資訊 + +`online`ç•¶å…ˆå‰é€£æŽ¥çš„行動è£ç½®æŽ¥æ”¶åˆ°ä¸€å€‹ç¶²è·¯é€£æŽ¥ä»¥å…許應用程å¼è¨ªå•互è¯ç¶²æ™‚激發的事件。 它ä¾è³´äºŽé€£æŽ¥ API,相åŒçš„資訊,則會激發 `connection.type` 從更改 `NONE` 為任何其他值。 + +應用程å¼é€šå¸¸æ‡‰ä½¿ç”¨ `document.addEventListener` å°‡ä¸€å€‹äº‹ä»¶æ””æˆªå™¨é™„åŠ ä¸€æ¬¡ `deviceready` 事件ç«ç½ã€‚ + +### 快速的示例 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 的怪癖 + +在åˆå§‹å•Ÿå‹•期間第一次 `online` 事件 (如果é©ç”¨ï¼‰ï¼Œè‡³å°‘需一秒的ç«ç½ä¹‹å‰çš„, `connection.type` 是`UNKNOWN`. + +### Windows Phone 7 的怪癖 + +ç•¶é‹è¡Œåœ¨æ¨¡æ“¬å™¨ä¸ï¼Œ `connection.status` å§‹çµ‚æ˜¯æœªçŸ¥çš„å› æ¤æ¤äº‹ä»¶ä¸æœƒ*ä¸*ç«ã€‚ + +### Windows Phone 8 怪癖 + +模擬程å¼å ±å‘Šé€£ç·šé¡žåž‹ç‚º `Cellular` ï¼Œè€Œä¸æœƒæ›´æ”¹ï¼Œæ‰€ä»¥äº‹ä»¶ä¸**ç«ã€‚ diff --git a/StoneIsland/plugins/cordova-plugin-network-information/package.json b/StoneIsland/plugins/cordova-plugin-network-information/package.json new file mode 100644 index 00000000..452db88b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/package.json @@ -0,0 +1,46 @@ +{ + "name": "cordova-plugin-network-information", + "version": "1.0.1", + "description": "Cordova Network Information Plugin", + "cordova": { + "id": "cordova-plugin-network-information", + "platforms": [ + "firefoxos", + "android", + "amazon-fireos", + "ubuntu", + "ios", + "blackberry10", + "wp7", + "wp8", + "windows8", + "windows", + "tizen", + "browser" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-network-information" + }, + "keywords": [ + "cordova", + "network", + "information", + "ecosystem:cordova", + "cordova-firefoxos", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-blackberry10", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows", + "cordova-tizen", + "cordova-browser" + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-network-information/plugin.xml b/StoneIsland/plugins/cordova-plugin-network-information/plugin.xml new file mode 100644 index 00000000..e0ed97fc --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/plugin.xml @@ -0,0 +1,174 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" +xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-network-information" + version="1.0.1"> + + <name>Network Information</name> + <description>Cordova Network Information Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,network,information</keywords> + <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-network-information.git</repo> + <issue>https://issues.apache.org/jira/browse/CB/component/12320640</issue> + + <js-module src="www/network.js" name="network"> + <clobbers target="navigator.connection" /> + <clobbers target="navigator.network.connection" /> + </js-module> + + <js-module src="www/Connection.js" name="Connection"> + <clobbers target="Connection" /> + </js-module> + + <!-- firefoxos --> + <platform name="firefoxos"> + <js-module src="src/firefoxos/NetworkProxy.js" name="NetworkProxy"> + <runs /> + </js-module> + </platform> + + <!-- android --> + <platform name="android"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="NetworkStatus"> + <param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager"/> + </feature> + </config-file> + + <config-file target="AndroidManifest.xml" parent="/*"> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + </config-file> + + <source-file src="src/android/NetworkManager.java" target-dir="src/org/apache/cordova/networkinformation" /> + + </platform> + + <!-- amazon-fireos --> + <platform name="amazon-fireos"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="NetworkStatus"> + <param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager"/> + </feature> + </config-file> + + <config-file target="AndroidManifest.xml" parent="/*"> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + </config-file> + + <source-file src="src/android/NetworkManager.java" target-dir="src/org/apache/cordova/networkinformation" /> + + </platform> + + + <!-- ubuntu --> + <platform name="ubuntu"> + <config-file target="config.xml" parent="/*"> + <feature name="Camera"> + <param policy_group="connectivity" policy_version="1" /> + </feature> + </config-file> + <header-file src="src/ubuntu/network_information.h" /> + <source-file src="src/ubuntu/network_information.cpp" /> + </platform> + + <!-- ios --> + <platform name="ios"> + <config-file target="config.xml" parent="/*"> + <feature name="NetworkStatus"> + <param name="ios-package" value="CDVConnection" /> + </feature> + </config-file> + + <header-file src="src/ios/CDVConnection.h" /> + <source-file src="src/ios/CDVConnection.m" /> + <header-file src="src/ios/CDVReachability.h" /> + <source-file src="src/ios/CDVReachability.m" /> + <framework src="SystemConfiguration.framework" weak="true" /> + </platform> + + <!-- blackberry10 --> + <platform name="blackberry10"> + <source-file src="src/blackberry10/index.js" target-dir="NetworkStatus" /> + <config-file target="www/config.xml" parent="/widget"> + <feature name="NetworkStatus" value="NetworkStatus"/> + </config-file> + </platform> + + <!-- wp7 --> + <platform name="wp7"> + <config-file target="config.xml" parent="/*"> + <feature name="NetworkStatus"> + <param name="wp-package" value="NetworkStatus"/> + </feature> + </config-file> + + <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> + <Capability Name="ID_CAP_NETWORKING" /> + </config-file> + + <source-file src="src/wp/NetworkStatus.cs" /> + </platform> + + <!-- wp8 --> + <platform name="wp8"> + <config-file target="config.xml" parent="/*"> + <feature name="NetworkStatus"> + <param name="wp-package" value="NetworkStatus"/> + </feature> + </config-file> + + <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> + <Capability Name="ID_CAP_NETWORKING" /> + </config-file> + + <source-file src="src/wp/NetworkStatus.cs" /> + </platform> + + <!-- windows8 --> + <platform name="windows8"> + <js-module src="src/windows/NetworkInfoProxy.js" name="NetworkInfoProxy"> + <merges target="" /> + </js-module> + </platform> + + <!-- windows --> + <platform name="windows"> + <js-module src="src/windows/NetworkInfoProxy.js" name="NetworkInfoProxy"> + <merges target="" /> + </js-module> + </platform> + + <!-- tizen --> + <platform name="tizen"> + <js-module src="src/tizen/NetworkProxy.js" name="NetworkProxy"> + <runs /> + </js-module> + </platform> + + <!-- browser --> + <platform name="browser"> + <js-module src="www/browser/network.js" name="browserNetwork"> + <clobbers target="navigator.connection" /> + <clobbers target="navigator.network.connection" /> + </js-module> + </platform> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/android/NetworkManager.java b/StoneIsland/plugins/cordova-plugin-network-information/src/android/NetworkManager.java new file mode 100755 index 00000000..4c85ddab --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/android/NetworkManager.java @@ -0,0 +1,267 @@ +/* + 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. +*/ +package org.apache.cordova.networkinformation; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.apache.cordova.CordovaWebView; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.util.Log; + +public class NetworkManager extends CordovaPlugin { + + public static int NOT_REACHABLE = 0; + public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; + public static int REACHABLE_VIA_WIFI_NETWORK = 2; + + public static final String WIFI = "wifi"; + public static final String WIMAX = "wimax"; + // mobile + public static final String MOBILE = "mobile"; + + // Android L calls this Cellular, because I have no idea! + public static final String CELLULAR = "cellular"; + // 2G network types + public static final String GSM = "gsm"; + public static final String GPRS = "gprs"; + public static final String EDGE = "edge"; + // 3G network types + public static final String CDMA = "cdma"; + public static final String UMTS = "umts"; + public static final String HSPA = "hspa"; + public static final String HSUPA = "hsupa"; + public static final String HSDPA = "hsdpa"; + public static final String ONEXRTT = "1xrtt"; + public static final String EHRPD = "ehrpd"; + // 4G network types + public static final String LTE = "lte"; + public static final String UMB = "umb"; + public static final String HSPA_PLUS = "hspa+"; + // return type + public static final String TYPE_UNKNOWN = "unknown"; + public static final String TYPE_ETHERNET = "ethernet"; + public static final String TYPE_WIFI = "wifi"; + public static final String TYPE_2G = "2g"; + public static final String TYPE_3G = "3g"; + public static final String TYPE_4G = "4g"; + public static final String TYPE_NONE = "none"; + + private static final String LOG_TAG = "NetworkManager"; + + private CallbackContext connectionCallbackContext; + + ConnectivityManager sockMan; + BroadcastReceiver receiver; + private JSONObject lastInfo = null; + + /** + * Sets the context of the Command. This can then be used to do things like + * get file paths associated with the Activity. + * + * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. + */ + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); + this.connectionCallbackContext = null; + + // We need to listen to connectivity events to update navigator.connection + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); + if (this.receiver == null) { + this.receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + // (The null check is for the ARM Emulator, please use Intel Emulator for better results) + if(NetworkManager.this.webView != null) + updateConnectionInfo(sockMan.getActiveNetworkInfo()); + } + }; + webView.getContext().registerReceiver(this.receiver, intentFilter); + } + + } + + /** + * Executes the request and returns PluginResult. + * + * @param action The action to execute. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback id used when calling back into JavaScript. + * @return True if the action was valid, false otherwise. + */ + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + if (action.equals("getConnectionInfo")) { + this.connectionCallbackContext = callbackContext; + NetworkInfo info = sockMan.getActiveNetworkInfo(); + String connectionType = ""; + try { + connectionType = this.getConnectionInfo(info).get("type").toString(); + } catch (JSONException e) { } + + PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType); + pluginResult.setKeepCallback(true); + callbackContext.sendPluginResult(pluginResult); + return true; + } + return false; + } + + /** + * Stop network receiver. + */ + public void onDestroy() { + if (this.receiver != null) { + try { + webView.getContext().unregisterReceiver(this.receiver); + } catch (Exception e) { + Log.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e); + } finally { + receiver = null; + } + } + } + + //-------------------------------------------------------------------------- + // LOCAL METHODS + //-------------------------------------------------------------------------- + + /** + * Updates the JavaScript side whenever the connection changes + * + * @param info the current active network info + * @return + */ + private void updateConnectionInfo(NetworkInfo info) { + // send update to javascript "navigator.network.connection" + // Jellybean sends its own info + JSONObject thisInfo = this.getConnectionInfo(info); + if(!thisInfo.equals(lastInfo)) + { + String connectionType = ""; + try { + connectionType = thisInfo.get("type").toString(); + } catch (JSONException e) { } + + sendUpdate(connectionType); + lastInfo = thisInfo; + } + } + + /** + * Get the latest network connection information + * + * @param info the current active network info + * @return a JSONObject that represents the network info + */ + private JSONObject getConnectionInfo(NetworkInfo info) { + String type = TYPE_NONE; + String extraInfo = ""; + if (info != null) { + // If we are not connected to any network set type to none + if (!info.isConnected()) { + type = TYPE_NONE; + } + else { + type = getType(info); + } + extraInfo = info.getExtraInfo(); + } + + Log.d("CordovaNetworkManager", "Connection Type: " + type); + Log.d("CordovaNetworkManager", "Connection Extra Info: " + extraInfo); + + JSONObject connectionInfo = new JSONObject(); + + try { + connectionInfo.put("type", type); + connectionInfo.put("extraInfo", extraInfo); + } catch (JSONException e) { } + + return connectionInfo; + } + + /** + * Create a new plugin result and send it back to JavaScript + * + * @param connection the network info to set as navigator.connection + */ + private void sendUpdate(String type) { + if (connectionCallbackContext != null) { + PluginResult result = new PluginResult(PluginResult.Status.OK, type); + result.setKeepCallback(true); + connectionCallbackContext.sendPluginResult(result); + } + webView.postMessage("networkconnection", type); + } + + /** + * Determine the type of connection + * + * @param info the network info so we can determine connection type. + * @return the type of mobile network we are on + */ + private String getType(NetworkInfo info) { + if (info != null) { + String type = info.getTypeName(); + + if (type.toLowerCase().equals(WIFI)) { + return TYPE_WIFI; + } + else if (type.toLowerCase().equals(MOBILE) || type.toLowerCase().equals(CELLULAR)) { + type = info.getSubtypeName(); + if (type.toLowerCase().equals(GSM) || + type.toLowerCase().equals(GPRS) || + type.toLowerCase().equals(EDGE)) { + return TYPE_2G; + } + else if (type.toLowerCase().startsWith(CDMA) || + type.toLowerCase().equals(UMTS) || + type.toLowerCase().equals(ONEXRTT) || + type.toLowerCase().equals(EHRPD) || + type.toLowerCase().equals(HSUPA) || + type.toLowerCase().equals(HSDPA) || + type.toLowerCase().equals(HSPA)) { + return TYPE_3G; + } + else if (type.toLowerCase().equals(LTE) || + type.toLowerCase().equals(UMB) || + type.toLowerCase().equals(HSPA_PLUS)) { + return TYPE_4G; + } + } + } + else { + return TYPE_NONE; + } + return TYPE_UNKNOWN; + } +} diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/blackberry10/index.js b/StoneIsland/plugins/cordova-plugin-network-information/src/blackberry10/index.js new file mode 100644 index 00000000..d47d840e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/blackberry10/index.js @@ -0,0 +1,64 @@ +/* + * + * 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 from BB10 to cordova connection types: +//https://github.com/apache/cordova-js/blob/master/lib/common/plugin/Connection.js +function mapConnectionType(con) { + switch (con.type) { + case 'wired': + return 'ethernet'; + case 'wifi': + return 'wifi'; + case 'none': + return 'none'; + case 'cellular': + switch (con.technology) { + case 'edge': + case 'gsm': + return '2g'; + case 'evdo': + return '3g'; + case 'umts': + return '3g'; + case 'lte': + return '4g'; + } + return "cellular"; + } + return 'unknown'; +} + +function currentConnectionType() { + try { + //possible for webplatform to throw pps exception + return mapConnectionType(window.qnx.webplatform.device.activeConnection || { type : 'none' }); + } + catch (e) { + return 'unknown'; + } +} + +module.exports = { + getConnectionInfo: function (success, fail, args, env) { + var result = new PluginResult(args, env); + result.ok(currentConnectionType()); + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js b/StoneIsland/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js new file mode 100644 index 00000000..40d61637 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js @@ -0,0 +1,97 @@ +/* + * + * 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. + * + */ + +/* + Network API overview: http://www.w3.org/TR/netinfo-api/ + and http://w3c.github.io/netinfo/ +*/ + +var cordova = require('cordova'), + Connection = require('./Connection'), + modulemapper = require('cordova/modulemapper'); + +var origConnection = modulemapper.getOriginalSymbol(window, 'navigator.connection'); + +module.exports = { + + getConnectionInfo: function(successCallback, errorCallback) { + var connection = origConnection || navigator.mozConnection, + connectionType = Connection.UNKNOWN; + + if (!connection) { + setTimeout(function() { + successCallback(connectionType); + }, 0); + return; + } + + var bandwidth = connection.bandwidth, + metered = connection.metered, + type = connection.type; + + if (type != undefined) { + // For more information see: + // https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API + + switch(type) { + case "cellular": + connectionType = Connection.CELL; + break; + case "ethernet": + connectionType = Connection.ETHERNET; + break; + case "wifi": + connectionType = Connection.WIFI; + break; + case "none": + connectionType = Connection.NONE; + break; + } + } else if (bandwidth != undefined && metered != undefined) { + /* + bandwidth of type double, readonly + The user agent must set the value of the bandwidth attribute to: + 0 if the user is currently offline; + Infinity if the bandwidth is unknown; + an estimation of the current bandwidth in MB/s (Megabytes per seconds) + available for communication with the browsing context active document's + domain. + + For more information see: + https://developer.mozilla.org/en-US/docs/Web/API/Connection + */ + + if (bandwidth === 0) { + connectionType = Connection.NONE; + } else if (metered && isFinite(bandwidth)) { + connectionType = Connection.CELL; + } else if (!metered && isFinite(bandwidth)) { + connectionType = Connection.WIFI; + } + } + + setTimeout(function() { + successCallback(connectionType); + }, 0); + } +}; + +require("cordova/exec/proxy").add("NetworkStatus", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h new file mode 100644 index 00000000..8add0279 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h @@ -0,0 +1,34 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import <Foundation/Foundation.h> +#import <Cordova/CDVPlugin.h> +#import "CDVReachability.h" + +@interface CDVConnection : CDVPlugin { + NSString* type; + NSString* _callbackId; + + CDVReachability* internetReach; +} + +@property (copy) NSString* connectionType; +@property (strong) CDVReachability* internetReach; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m new file mode 100644 index 00000000..37497675 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m @@ -0,0 +1,127 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVConnection.h" +#import "CDVReachability.h" + +@interface CDVConnection (PrivateMethods) +- (void)updateOnlineStatus; +- (void)sendPluginResult; +@end + +@implementation CDVConnection + +@synthesize connectionType, internetReach; + +- (void)getConnectionInfo:(CDVInvokedUrlCommand*)command +{ + _callbackId = command.callbackId; + [self sendPluginResult]; +} + +- (void)sendPluginResult +{ + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType]; + + [result setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:result callbackId:_callbackId]; +} + +- (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability +{ + NetworkStatus networkStatus = [reachability currentReachabilityStatus]; + + switch (networkStatus) { + case NotReachable: + return @"none"; + + case ReachableViaWWAN: + { + BOOL isConnectionRequired = [reachability connectionRequired]; + if (isConnectionRequired) { + return @"none"; + } else { + return @"cellular"; + } + } + case ReachableViaWiFi: + return @"wifi"; + + default: + return @"unknown"; + } +} + +- (BOOL)isCellularConnection:(NSString*)theConnectionType +{ + return [theConnectionType isEqualToString:@"2g"] || + [theConnectionType isEqualToString:@"3g"] || + [theConnectionType isEqualToString:@"4g"] || + [theConnectionType isEqualToString:@"cellular"]; +} + +- (void)updateReachability:(CDVReachability*)reachability +{ + if (reachability) { + // check whether the connection type has changed + NSString* newConnectionType = [self w3cConnectionTypeFor:reachability]; + if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes + return; + } else { + self.connectionType = [self w3cConnectionTypeFor:reachability]; + } + } + [self sendPluginResult]; +} + +- (void)updateConnectionType:(NSNotification*)note +{ + CDVReachability* curReach = [note object]; + + if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) { + [self updateReachability:curReach]; + } +} + +- (void)onPause +{ + [self.internetReach stopNotifier]; +} + +- (void)onResume +{ + [self.internetReach startNotifier]; + [self updateReachability:self.internetReach]; +} + +- (void)pluginInitialize +{ + self.connectionType = @"none"; + self.internetReach = [CDVReachability reachabilityForInternetConnection]; + self.connectionType = [self w3cConnectionTypeFor:self.internetReach]; + [self.internetReach startNotifier]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) + name:kReachabilityChangedNotification object:nil]; + if (&UIApplicationDidEnterBackgroundNotification && &UIApplicationWillEnterForegroundNotification) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; + } +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h new file mode 100644 index 00000000..01a95c35 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h @@ -0,0 +1,85 @@ +/* + + File: Reachability.h + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import <Foundation/Foundation.h> +#import <SystemConfiguration/SystemConfiguration.h> +#import <netinet/in.h> + +typedef enum { + NotReachable = 0, + ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons + ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons +} NetworkStatus; +#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" + +@interface CDVReachability : NSObject +{ + BOOL localWiFiRef; + SCNetworkReachabilityRef reachabilityRef; +} + +// reachabilityWithHostName- Use to check the reachability of a particular host name. ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; + +// reachabilityWithAddress- Use to check the reachability of a particular IP address. ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; + +// reachabilityForInternetConnection- checks whether the default route is available. +// Should be used by applications that do not connect to a particular host ++ (CDVReachability*)reachabilityForInternetConnection; + +// reachabilityForLocalWiFi- checks whether a local wifi connection is available. ++ (CDVReachability*)reachabilityForLocalWiFi; + +// Start listening for reachability notifications on the current run loop +- (BOOL)startNotifier; +- (void)stopNotifier; + +- (NetworkStatus)currentReachabilityStatus; +// WWAN may be available, but not active until a connection has been established. +// WiFi may require a connection for VPN on Demand. +- (BOOL)connectionRequired; +@end diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m new file mode 100644 index 00000000..c60261ae --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m @@ -0,0 +1,260 @@ +/* + + File: Reachability.m + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import <sys/socket.h> +#import <netinet/in.h> +#import <netinet6/in6.h> +#import <arpa/inet.h> +#import <ifaddrs.h> +#import <netdb.h> + +#import <CoreFoundation/CoreFoundation.h> + +#import "CDVReachability.h" + +#define kShouldPrintReachabilityFlags 0 + +static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) +{ +#if kShouldPrintReachabilityFlags + NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", + (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', + (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', + + (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', + (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', + (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', + (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', + comment + ); +#endif +} + +@implementation CDVReachability + +static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) +{ +#pragma unused (target, flags) + // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); + // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); + + // Converted the asserts above to conditionals, with safe return from the function + if (info == NULL) { + NSLog(@"info was NULL in ReachabilityCallback"); + return; + } + + if (![(__bridge NSObject*)info isKindOfClass :[CDVReachability class]]) { + NSLog(@"info was wrong class in ReachabilityCallback"); + return; + } + + // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively + // in case someon uses the Reachability object in a different thread. + @autoreleasepool { + CDVReachability* noteObject = (__bridge CDVReachability*)info; + // Post a notification to notify the client that the network reachability changed. + [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject]; + } +} + +- (BOOL)startNotifier +{ + BOOL retVal = NO; + SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL}; + + if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) { + if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { + retVal = YES; + } + } + return retVal; +} + +- (void)stopNotifier +{ + if (reachabilityRef != NULL) { + SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); + } +} + +- (void)dealloc +{ + [self stopNotifier]; + if (reachabilityRef != NULL) { + CFRelease(reachabilityRef); + } +} + ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; +{ + CDVReachability* retVal = NULL; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + retVal->localWiFiRef = NO; + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; +{ + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); + CDVReachability* retVal = NULL; + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + retVal->localWiFiRef = NO; + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityForInternetConnection; +{ + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; + return [self reachabilityWithAddress:&zeroAddress]; +} + ++ (CDVReachability*)reachabilityForLocalWiFi; +{ + struct sockaddr_in localWifiAddress; + bzero(&localWifiAddress, sizeof(localWifiAddress)); + localWifiAddress.sin_len = sizeof(localWifiAddress); + localWifiAddress.sin_family = AF_INET; + // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 + localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); + CDVReachability* retVal = [self reachabilityWithAddress:&localWifiAddress]; + if (retVal != NULL) { + retVal->localWiFiRef = YES; + } + return retVal; +} + +#pragma mark Network Flag Handling + +- (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "localWiFiStatusForFlags"); + + BOOL retVal = NotReachable; + if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) { + retVal = ReachableViaWiFi; + } + return retVal; +} + +- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "networkStatusForFlags"); + if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { + // if target host is not reachable + return NotReachable; + } + + NetworkStatus retVal = NotReachable; + + if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) { + // if target host is reachable and no connection is required + // then we'll assume (for now) that your on Wi-Fi + retVal = ReachableViaWiFi; + } + + if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) || + ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) { + // ... and the connection is on-demand (or on-traffic) if the + // calling application is using the CFSocketStream or higher APIs + + if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) { + // ... and no [user] intervention is needed + retVal = ReachableViaWiFi; + } + } + + if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) { + // ... but WWAN connections are OK if the calling application + // is using the CFNetwork (CFSocketStream?) APIs. + retVal = ReachableViaWWAN; + } + return retVal; +} + +- (BOOL)connectionRequired; +{ + NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + return flags & kSCNetworkReachabilityFlagsConnectionRequired; + } + return NO; +} + +- (NetworkStatus)currentReachabilityStatus +{ + NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); + NetworkStatus retVal = NotReachable; + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + if (localWiFiRef) { + retVal = [self localWiFiStatusForFlags:flags]; + } else { + retVal = [self networkStatusForFlags:flags]; + } + } + return retVal; +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js b/StoneIsland/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js new file mode 100644 index 00000000..cd9506e1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js @@ -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. + * +*/ + +var cordova = require('cordova'); +var Connection = require('./Connection'); + +module.exports = { + getConnectionInfo: function(successCallback, errorCallback) { + var cncType = Connection.NONE; + var infoCount = 0; + var deviceCapabilities = null; + var timerId = 0; + var timeout = 300; + + + function connectionCB() { + if (timerId !== null) { + clearTimeout(timerId); + timerId = null; + } + + infoCount++; + + if (infoCount > 1) { + if (successCallback) { + successCallback(cncType); + } + } + } + + function errorCB(error) { + console.log("Error: " + error.code + "," + error.name + "," + error.message); + + if (errorCallback) { + errorCallback(); + } + } + + function wifiSuccessCB(wifi) { + if ((wifi.status === "ON") && (wifi.ipAddress.length !== 0)) { + cncType = Connection.WIFI; + } + connectionCB(); + } + + function cellularSuccessCB(cell) { + if ((cncType === Connection.NONE) && (cell.status === "ON") && (cell.ipAddress.length !== 0)) { + cncType = Connection.CELL_2G; + } + connectionCB(); + } + + + deviceCapabilities = tizen.systeminfo.getCapabilities(); + + + timerId = setTimeout(function() { + timerId = null; + infoCount = 1; + connectionCB(); + }, timeout); + + + if (deviceCapabilities.wifi) { + tizen.systeminfo.getPropertyValue("WIFI_NETWORK", wifiSuccessCB, errorCB); + } + + if (deviceCapabilities.telephony) { + tizen.systeminfo.getPropertyValue("CELLULAR_NETWORK", cellularSuccessCB, errorCB); + } + } +}; + +require("cordova/tizen/commandProxy").add("NetworkStatus", module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp b/StoneIsland/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp new file mode 100644 index 00000000..8fdb4949 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp @@ -0,0 +1,63 @@ +/* + * Licensed 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 "network_information.h" + +void NetworkInformation::getConnectionInfo(int scId, int ecId) { + Q_UNUSED(ecId); + + QString result; + QNetworkInfo::NetworkMode networkMode = m_systemNetworkInfo.currentNetworkMode(); + QNetworkInfo::NetworkStatus networkStatus = m_systemNetworkInfo.networkStatus(networkMode, 0); + QNetworkInfo::CellDataTechnology cellDataTechnology = m_systemNetworkInfo.currentCellDataTechnology(0); + + if (networkStatus == QNetworkInfo::NoNetworkAvailable) + result = "Connection.NONE"; + + switch (networkMode) { + case QNetworkInfo::WimaxMode: + case QNetworkInfo::WlanMode: + result = "Connection.WIFI"; + break; + case QNetworkInfo::EthernetMode: + result = "Connection.ETHERNET"; + break; + case QNetworkInfo::LteMode: + result = "Connection.CELL_4G"; + break; + case QNetworkInfo::GsmMode: + case QNetworkInfo::CdmaMode: + case QNetworkInfo::TdscdmaMode: + case QNetworkInfo::WcdmaMode: + switch (cellDataTechnology) { + case QNetworkInfo::UmtsDataTechnology: + case QNetworkInfo::HspaDataTechnology: + result = "Connection.CELL_3G"; + break; + case QNetworkInfo::EdgeDataTechnology: + case QNetworkInfo::GprsDataTechnology: + result = "Connection.CELL_2G"; + break; + case QNetworkInfo::UnknownDataTechnology: + result = "Connection.UNKNOWN"; + break; + } + case QNetworkInfo::BluetoothMode: + case QNetworkInfo::UnknownMode: + result = "Connection.UNKNOWN"; + break; + } + + this->callback(scId, result); +} diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h b/StoneIsland/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h new file mode 100644 index 00000000..aca20e7b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h @@ -0,0 +1,47 @@ +/* + * Licensed 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 NETWORK_INFORMATION_H +#define NETWORK_INFORMATION_H + +#include <cplugin.h> + +#include <QtSystemInfo> +#include <QtCore> + +class NetworkInformation: public CPlugin { + Q_OBJECT +public: + explicit NetworkInformation(Cordova *cordova): CPlugin(cordova) {} + + virtual const QString fullName() override { + return NetworkInformation::fullID(); + } + + virtual const QString shortName() override { + return "Connection"; + } + + static const QString fullID() { + return "NetworkStatus"; + } + +public slots: + void getConnectionInfo(int scId, int ecId); + +private: + QNetworkInfo m_systemNetworkInfo; +}; + +#endif diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js b/StoneIsland/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js new file mode 100644 index 00000000..27ad2f06 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js @@ -0,0 +1,88 @@ +/* + * + * 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 Windows:true */ + +var cordova = require('cordova'); +var Connection = require('./Connection'); + +var winNetConn = Windows.Networking.Connectivity; +var networkInfo = winNetConn.NetworkInformation; +var networkCostInfo = winNetConn.NetworkCostType; +var networkConnectivityInfo = winNetConn.NetworkConnectivityLevel; +var networkAuthenticationInfo = winNetConn.NetworkAuthenticationType; +var networkEncryptionInfo = winNetConn.NetworkEncryptionType; + +function getCurrrentConnectionType() { + + var profile = networkInfo.getInternetConnectionProfile(); + + if (!profile) { + return Connection.NONE; + } + + var conLevel = profile.getNetworkConnectivityLevel(); + var interfaceType = profile.networkAdapter.ianaInterfaceType; + + // since we use this to detect whether we are online or offline we do check agains InternetAccess + // localAccess (airplane mode as an example) or constrainedInternetAccess mean there is no access to the internet available + // https://msdn.microsoft.com/library/windows/apps/windows.networking.connectivity.networkconnectivitylevel.aspx + if (conLevel != Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) { + return Connection.NONE; + } + + var connectionType; + + switch (interfaceType) { + case 71: + connectionType = Connection.WIFI; + break; + case 6: + connectionType = Connection.ETHERNET; + break; + case 243: // (3GPP WWAN) // Fallthrough is intentional + case 244: // (3GPP2 WWAN) + connectionType = Connection.CELL_3G; + break; + default: + connectionType = Connection.UNKNOWN; + break; + } + + return connectionType; +} + +module.exports = { + + getConnectionInfo:function(win,fail,args) + { + var reportConnectionInfoOnce = function () { + win(getCurrrentConnectionType(), { keepCallback: true }); + } + + // report current connection type + setTimeout(reportConnectionInfoOnce, 0); + // start traking future changes + networkInfo.addEventListener("networkstatuschanged", reportConnectionInfoOnce); + } +}; + +require("cordova/exec/proxy").add("NetworkStatus",module.exports); diff --git a/StoneIsland/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs b/StoneIsland/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs new file mode 100644 index 00000000..12eb061d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs @@ -0,0 +1,129 @@ +/* + Licensed 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. +*/ + +using System; +using System.Diagnostics; +using System.Net; +using System.Net.NetworkInformation; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; +using Microsoft.Phone.Net.NetworkInformation; + +namespace WPCordovaClassLib.Cordova.Commands +{ + + // http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation(v=VS.92).aspx + // http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.devicenetworkinformation(v=VS.92).aspx + + public class NetworkStatus : BaseCommand + { + const string UNKNOWN = "unknown"; + const string ETHERNET = "ethernet"; + const string WIFI = "wifi"; + const string CELL_2G = "2g"; + const string CELL_3G = "3g"; + const string CELL_4G = "4g"; + const string NONE = "none"; + const string CELL = "cellular"; + + private bool HasCallback = false; + + public NetworkStatus() + { + DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(ChangeDetected); + } + + public override void OnResume(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) + { + this.getConnectionInfo(""); + } + + public void getConnectionInfo(string empty) + { + HasCallback = true; + updateConnectionType(checkConnectionType()); + } + + private string checkConnectionType() + { + if (DeviceNetworkInformation.IsNetworkAvailable) + { + if (DeviceNetworkInformation.IsWiFiEnabled) + { + return WIFI; + } + else + { + return DeviceNetworkInformation.IsCellularDataEnabled ? CELL : UNKNOWN; + } + } + return NONE; + } + + private string checkConnectionType(NetworkInterfaceSubType type) + { + switch (type) + { + case NetworkInterfaceSubType.Cellular_1XRTT: //cell + case NetworkInterfaceSubType.Cellular_GPRS: //cell + return CELL; + case NetworkInterfaceSubType.Cellular_EDGE: //2 + return CELL_2G; + case NetworkInterfaceSubType.Cellular_3G: + case NetworkInterfaceSubType.Cellular_EVDO: //3 + case NetworkInterfaceSubType.Cellular_EVDV: //3 + case NetworkInterfaceSubType.Cellular_HSPA: //3 + return CELL_3G; + case NetworkInterfaceSubType.WiFi: + return WIFI; + case NetworkInterfaceSubType.Unknown: + case NetworkInterfaceSubType.Desktop_PassThru: + default: + return UNKNOWN; + } + } + + void ChangeDetected(object sender, NetworkNotificationEventArgs e) + { + switch (e.NotificationType) + { + case NetworkNotificationType.InterfaceConnected: + updateConnectionType(checkConnectionType(e.NetworkInterface.InterfaceSubtype)); + break; + case NetworkNotificationType.InterfaceDisconnected: + updateConnectionType(NONE); + break; + default: + break; + } + } + + private void updateConnectionType(string type) + { + // This should also implicitly fire offline/online events as that is handled on the JS side + if (this.HasCallback) + { + PluginResult result = new PluginResult(PluginResult.Status.OK, type); + result.KeepCallback = true; + DispatchCommandResult(result); + } + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-network-information/tests/plugin.xml b/StoneIsland/plugins/cordova-plugin-network-information/tests/plugin.xml new file mode 100644 index 00000000..8df4769c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/tests/plugin.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + xmlns:android="http://schemas.android.com/apk/res/android" + id="cordova-plugin-network-information-tests" + version="1.0.1"> + <name>Cordova Network Information Plugin Tests</name> + <license>Apache 2.0</license> + + <js-module src="tests.js" name="tests"> + </js-module> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-network-information/tests/tests.js b/StoneIsland/plugins/cordova-plugin-network-information/tests/tests.js new file mode 100644 index 00000000..23be97ac --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/tests/tests.js @@ -0,0 +1,101 @@ +/* + * + * 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.defineAutoTests = function () { + describe('Network (navigator.connection)', function () { + it("network.spec.1 should exist", function () { + expect(navigator.network && navigator.network.connection).toBeDefined(); + expect(navigator.connection).toBeDefined(); + }); + + it("network.spec.2 should be set to a valid value", function () { + var validValues = { + 'unknown': 1, + 'ethernet': 1, + 'wifi': 1, + '2g': 1, + 'cellular': 1, + '3g': 1, + '4g': 1, + 'none': 1 + }; + expect(validValues[navigator.connection.type]).toBe(1); + }); + + it("network.spec.3 should have the same value in deprecated and non-deprecated apis", function () { + expect(navigator.network.connection.type).toBe(navigator.connection.type); + }); + + it("network.spec.4 should define constants for connection status", function () { + expect(Connection.UNKNOWN).toBe("unknown"); + expect(Connection.ETHERNET).toBe("ethernet"); + expect(Connection.WIFI).toBe("wifi"); + expect(Connection.CELL_2G).toBe("2g"); + expect(Connection.CELL_3G).toBe("3g"); + expect(Connection.CELL_4G).toBe("4g"); + expect(Connection.NONE).toBe("none"); + expect(Connection.CELL).toBe("cellular"); + }); + }); +}; + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +exports.defineManualTests = function (contentEl, createActionButton) { + function eventOutput(s) { + var el = document.getElementById("results"); + el.innerHTML = el.innerHTML + s + "<br>"; + } + + function printNetwork() { + eventOutput("navigator.connection.type=" + navigator.connection.type); + eventOutput("navigator.network.connection.type=" + navigator.network.connection.type); + } + + function onEvent(e) { + eventOutput('Event of type: ' + e.type); + printNetwork(); + } + + /******************************************************************************/ + + var html = '<div id="info">' + + '<b>Results:</b><br>' + + '<span id="results"></span>' + + '</div><div id="connection"></div>' + + 'Expected result: Status box will update with type of connection using two different methods. Both values must match.' + + ' The result will be unknown, ethernet, wifi, 2g, 3g, 4g, none, or cellular. Make sure it matches what the device is connected to.' + + '</p> <div id="actions"></div>'; + + document.addEventListener("online", onEvent, false); + document.addEventListener("offline", onEvent, false); + contentEl.innerHTML = html; + + createActionButton('Show Network Connection', function () { + printNetwork(); + }, 'connection'); + + createActionButton('Clear Log', function () { + document.getElementById('results').innerHTML = ''; + }, 'actions'); +}; diff --git a/StoneIsland/plugins/cordova-plugin-network-information/www/Connection.js b/StoneIsland/plugins/cordova-plugin-network-information/www/Connection.js new file mode 100644 index 00000000..f20a485c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/www/Connection.js @@ -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. + * +*/ + +/** + * Network status + */ +module.exports = { + UNKNOWN: "unknown", + ETHERNET: "ethernet", + WIFI: "wifi", + CELL_2G: "2g", + CELL_3G: "3g", + CELL_4G: "4g", + CELL:"cellular", + NONE: "none" +}; diff --git a/StoneIsland/plugins/cordova-plugin-network-information/www/browser/network.js b/StoneIsland/plugins/cordova-plugin-network-information/www/browser/network.js new file mode 100644 index 00000000..72ec5139 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/www/browser/network.js @@ -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. + * +*/ + +/*global module, require*/ + +var cordova = require('cordova'), + Connection = require('./Connection'); + +var DOCUMENT_EVENTS_CHECK_INTERVAL = 500; // ms +// Flag that indicates that ew need to re-fire online/offline events at document level +// (Workaround for Chrome, since it fires such events only for window object) +var NEED_FIRE_DOCUMENT_EVENT_MANUALLY = false; + +function NetworkConnection() { + this.type = Connection.UNKNOWN; +} + +/** + * Get connection info + * + * @param {Function} successCallback The function to call when the Connection data is available + */ +NetworkConnection.prototype.getInfo = function(successCallback) { + successCallback(this.type); +}; + +Object.defineProperty(NetworkConnection.prototype, 'type', { + get: function () { + // It is not possible to determine real connection type in browser + // so we always report Connection.UNKNOWN when online + return (window.navigator.onLine === false ? Connection.NONE : Connection.UNKNOWN); + }, + configurable: true, + enumerable: true +}); + +// This function tries to detect if document online/offline events is being fired +// after corresponding window events, and if not, then fires them manually +// This is workaround for Chrome, which fires only window online/offline events +// and regarding to plugin spec we need these events at document object +var eventRedirectHandler = function (e) { + // NEED_FIRE_DOCUMENT_EVENT_MANUALLY flag is already set, + // just fire corresponding document event and return + if (NEED_FIRE_DOCUMENT_EVENT_MANUALLY) { + cordova.fireDocumentEvent(e.type); + return; + } + + // Flag that indicates whether corresponding document even is fired + var documentStateEventFired = false; + var setDocumentStateEventFired = function() { + documentStateEventFired = true; + }; + document.addEventListener(e.type, setDocumentStateEventFired); + setTimeout(function () { + // Remove unnecessary listener + document.removeEventListener(e.type, setDocumentStateEventFired); + // if document event hasn't been fired in specified interval (500 ms by default), + // then we're in chrome and need to fire it manually + if (!documentStateEventFired) { + NEED_FIRE_DOCUMENT_EVENT_MANUALLY = true; + cordova.fireDocumentEvent(e.type); + } + }, DOCUMENT_EVENTS_CHECK_INTERVAL); +}; + +// Subscribe to native online/offline events +window.addEventListener('online', eventRedirectHandler); +window.addEventListener('offline', eventRedirectHandler); + +var me = new NetworkConnection(); + +require("cordova/exec/proxy").add("NetworkStatus", { getConnectionInfo: me.getConnectionInfo }); + +module.exports = me; diff --git a/StoneIsland/plugins/cordova-plugin-network-information/www/network.js b/StoneIsland/plugins/cordova-plugin-network-information/www/network.js new file mode 100644 index 00000000..ac792d8c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-network-information/www/network.js @@ -0,0 +1,91 @@ +/* + * 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'), + cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'); + +// Link the onLine property with the Cordova-supplied network info. +// This works because we clobber the navigator object with our own +// object in bootstrap.js. +// Browser platform do not need to define this property, because +// it is already supported by modern browsers +if (cordova.platformId !== 'browser' && typeof navigator != 'undefined') { + utils.defineGetter(navigator, 'onLine', function() { + return this.connection.type != 'none'; + }); +} + +function NetworkConnection() { + this.type = 'unknown'; +} + +/** + * Get connection info + * + * @param {Function} successCallback The function to call when the Connection data is available + * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL) + */ +NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) { + exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []); +}; + +var me = new NetworkConnection(); +var timerId = null; +var timeout = 500; + +channel.createSticky('onCordovaConnectionReady'); +channel.waitForInitialization('onCordovaConnectionReady'); + +channel.onCordovaReady.subscribe(function() { + me.getInfo(function(info) { + me.type = info; + if (info === "none") { + // set a timer if still offline at the end of timer send the offline event + timerId = setTimeout(function(){ + cordova.fireDocumentEvent("offline"); + timerId = null; + }, timeout); + } else { + // If there is a current offline event pending clear it + if (timerId !== null) { + clearTimeout(timerId); + timerId = null; + } + cordova.fireDocumentEvent("online"); + } + + // should only fire this once + if (channel.onCordovaConnectionReady.state !== 2) { + channel.onCordovaConnectionReady.fire(); + } + }, + function (e) { + // If we can't get the network info we should still tell Cordova + // to fire the deviceready event. + if (channel.onCordovaConnectionReady.state !== 2) { + channel.onCordovaConnectionReady.fire(); + } + console.log("Error initializing Network Connection: " + e); + }); +}); + +module.exports = me; diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-splashscreen/CONTRIBUTING.md new file mode 100644 index 00000000..f7dbcaba --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/LICENSE b/StoneIsland/plugins/cordova-plugin-splashscreen/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/NOTICE b/StoneIsland/plugins/cordova-plugin-splashscreen/NOTICE new file mode 100644 index 00000000..8ec56a52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/README.md new file mode 100644 index 00000000..b43c2c59 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/README.md @@ -0,0 +1,131 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +This plugin displays and hides a splash screen during application launch. + +## Installation + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + +## Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- iOS +- Windows Phone 7 and 8 +- Windows 8 +- Windows +- Browser + + +## Methods + +- splashscreen.show +- splashscreen.hide + +### Android Quirks + +In your `config.xml`, you need to add the following preferences: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + +Where foo is the name of the splashscreen file, preferably a 9 patch file. Make sure to add your splashcreen files to your res/xml directory under the appropriate folders. The second parameter represents how long the splashscreen will appear in milliseconds. It defaults to 3000 ms. See [Icons and Splash Screens](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) +for more information. + +"SplashMaintainAspectRatio" preference is optional. If set to true, splash screen drawable is not stretched to fit screen, but instead simply "covers" the screen, like CSS "background-size:cover". This is very useful when splash screen images cannot be distorted in any way, for example when they contain scenery or text. This setting works best with images that have large margins (safe areas) that can be safely cropped on screens with different aspect ratios. + +The plugin reloads splash drawable whenever orientation changes, so you can specify different drawables for portrait and landscape orientations. + +### Browser Quirks + +You can use the following preferences in your `config.xml`: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS Quirks + +- `FadeSplashScreen` (boolean, defaults to `true`): Set to `false` to + prevent the splash screen from fading in and out when its display + state changes. + + <preference name="FadeSplashScreen" value="false"/> + +- `FadeSplashScreenDuration` (float, defaults to `2`): Specifies the + number of seconds for the splash screen fade effect to execute. + + <preference name="FadeSplashScreenDuration" value="4"/> + +- `ShowSplashScreenSpinner` (boolean, defaults to `true`): Set to `false` + to hide the splash-screen spinner. + + <preference name="ShowSplashScreenSpinner" value="false"/> + +## splashscreen.hide + +Dismiss the splash screen. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +The `config.xml` file's `AutoHideSplashScreen` setting must be +`false`. To delay hiding the splash screen for two seconds, add a +timer such as the following in the `deviceready` event handler: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + +## splashscreen.show + +Displays the splash screen. + + navigator.splashscreen.show(); + + +Your application cannot call `navigator.splashscreen.show()` until the app has +started and the `deviceready` event has fired. But since typically the splash +screen is meant to be visible before your app has started, that would seem to +defeat the purpose of the splash screen. Providing some configuration in +`config.xml` will automatically `show` the splash screen immediately after your +app launch and before it has fully started and received the `deviceready` +event. See [Icons and Splash Screens](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) +for more information on doing this configuration. For this reason, it is +unlikely you need to call `navigator.splashscreen.show()` to make the splash +screen visible for app startup. + diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-splashscreen/RELEASENOTES.md new file mode 100644 index 00000000..2c6b0013 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/RELEASENOTES.md @@ -0,0 +1,143 @@ +<!-- +# +# 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. +# +--> +# Release Notes + +### 0.2.2 (Sept 25, 2013) +* CB-4889 bumping&resetting version +* CB-4889 renaming org.apache.cordova.core.splashscreen to org.apache.cordova.splashscreen +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4806] Update splashscreen image bounds for iOS 7 +* [CB-4752] Incremented plugin version on dev branch. + +### 0.2.3 (Oct 9, 2013) +* [CB-4806] Re-fix Update splashscreen image bounds for iOS 7 +* [CB-4934] plugin-splashscreen should not show by default on Windows8 +* [CB-4929] plugin-splashscreen not loading proxy windows8 +* [CB-4915] Incremented plugin version on dev branch. + +### 0.2.4 (Oct 28, 2013) +* CB-5128: add repo + issue tag to plugin.xml for splashscreen plugin +* [CB-5010] Incremented plugin version on dev branch. + +### 0.2.5 (Dec 4, 2013) +* add ubuntu platform +* Added amazon-fireos platform. Change to use amazon-fireos as a platform if the user agent string contains 'cordova-amazon-fireos' +* CB-5124 - Remove splashscreen config.xml values from iOS Configuration Docs, move to plugin docs + +### 0.2.6 (Jan 02, 2014) +* CB-5658 Add doc/index.md for Splashscreen plugin +* Handle error when splash image is missing. + +### 0.2.7 (Feb 05, 2014) +* [CB-3562] Fix aspect ratio on landscape-only iPhone applications +* CB-4051 fix for splashscreen rotation problem + +### 0.3.0 (Apr 17, 2014) +* Add Tizen support to plugin +* CB-6422: [windows8] use cordova/exec/proxy +* CB-4051: [ios] - Re-fix - Splashscreen rotation problem (closes #13) +* CB-6460: Update license headers +* CB-6465: Add license headers to Tizen code +* Add NOTICE file + +### 0.3.1 (Jun 05, 2014) +* documentation translation: cordova-plugin-splashscreen +* Lisa testing pulling in plugins for plugin: cordova-plugin-splashscreen +* Lisa testing pulling in plugins for plugin: cordova-plugin-splashscreen +* Lisa testing pulling in plugins for plugin: cordova-plugin-splashscreen +* Lisa testing pulling in plugins for plugin: cordova-plugin-splashscreen +* CB-6810 Add license to CONTRIBUTING.md +* [wp8] updated quirk for and combined iOS,WP8,BB10 quirks as they are all the same +* [wp] implemented OnInit so splash screen can be shown before cordova page is loaded +* [wp] plugin must be autoloaded for AutoHideSplashScreen preference to work +* CB-6483 Use splash screen image from manifest on Windows8 +* CB-6491 add CONTRIBUTING.md +* Revert "Merge branch 'tizen' of http://github.com/siovene/cordova-plugin-splashscreen" + +### 0.3.2 (Aug 06, 2014) +* CB-6127 Updated translations for docs +* CB-7041 ios: Fix image filename logic when setting the iPad splash screen +* fixes Splashscreen crash on WP8 +* Remove outdated doc + +### 0.3.3 (Sep 17, 2014) +* CB-7249 cordova-plugin-splashscreen documentation translation +* Renamed test dir, added nested plugin.xml +* added documentation for manual tests +* CB-7196 port splashscreen tests to framework + +### 0.3.4 (Oct 03, 2014) +* Finalized iOS splash screen (image name) tests. 176 tests in all, 44 for each type of device (iPad, iPhone, iPhone5, iPhone6, iPhone 6 Plus). +* CB-7633 - (Re-fix based on updated unit tests) iPhone 6 Plus support +* Updated iOS tests for locked orientations +* Added more iOS splash screen tests. +* CB-7633 - Add support for iPhone 6/6+ +* Added failing iPhone 6/6 Plus tests. +* Added 'npm test' +* CB-7663 - iOS unit tests for splash screen +* Properly formatted splashscreen preference docs. + +### 0.3.5 (Dec 02, 2014) +* CB-7204 - Race condition when hiding and showing spinner (closes #21) +* CB-7700 cordova-plugin-splashscreen documentation translation: cordova-plugin-splashscreen + +### 1.0.0 (Feb 04, 2015) +* CB-8351 ios: Stop using deprecated IsIpad macro +* CB-3679 Add engine tag for Android >= 3.6.0 due to use of `preferences` +* CB-3679 Make SplashScreen plugin compatible with cordova-android@4.0.x + +### 2.0.0 (Apr 15, 2015) +* give users a way to install the bleeding edge. +* CB-8746 gave plugin major version bump +* CB-8797 - Splashscreen preferences FadeSplashScreenDuration and FadeSplashScreen (iOS) are missing +* CB-8836 - Crashes after animating splashscreen +* CB-8753 android: Fix missing import in previous commit +* CB-8753 android: Adds `SplashMaintainAspectRatio` preference (close #43) +* CB-8683 changed plugin-id to pacakge-name +* CB-8653 properly updated translated docs to use new id +* CB-8653 updated translated docs to use new id +* CB-8345 Make default for splashscreen resource "screen" (which is what template and CLI assume it to be) +* Revert "CB-8345 android: Make "splash" the default resource ID instead of null" +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* CB-8345 android: Make "splash" the default resource ID instead of null +* docs: added Windows to supported platforms +* CB-7964 Add cordova-plugin-splashscreen support for browser platform +* CB-8653 Updated Readme +* [wp8] oops, Added back config parse result checks +* [WP8] code cleanup, minor refactors, comments to clarify some stuff. +* Extend WP8 Splash Screen to respect SplashScreen and SplashScreenDelay preferences from config file +* CB-8574 Integrate TravisCI +* CB-8438 cordova-plugin-splashscreen documentation translation: cordova-plugin-splashscreen +* CB-8538 Added package.json file +* CB-8397 Add support to 'windows' for showing the Windows Phone splashscreen + +### 2.1.0 (Jun 17, 2015) +* added missing license headers +* CB-9128 cordova-plugin-splashscreen documentation translation: cordova-plugin-splashscreen +* fix npm md issue +* Fixed iOS unit tests. +* CB-3562: Disable screen rotation for iPhone when splash screen is shown. (closes #47) +* CB-8988: Fix rotation on iOS/iPad (closes #46) +* CB-8904: Don't reset the static variable when it's destroyed, otherwise we might as well just have a member variable +* Removed wp7 from plugin.xml and package.json +* CB-8750 [wp8]: Rewrite resoultion helper +* CB-8750 [wp8]: Allow resolution-specific splashscreen images +* CB-8758 [wp8]: UnauthorizedAccessException on hide() diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/de/README.md new file mode 100644 index 00000000..f876eff8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/de/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +Dieses Plugin zeigt und verbirgt einen Splash-Screen beim Start der Anwendung. + +## Installation + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * iOS + * Windows Phone 7 und 8 + * Windows 8 + * Windows + * Browser + +## Methoden + + * SplashScreen.Show + * SplashScreen.Hide + +### Android Eigenarten + +Sie müssen in Ihrem `"config.xml"`fügen Sie die folgenden Einstellungen: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +Wo Foo ist der Name der Datei Splashscreen, vorzugsweise eine 9-Patch-Datei. Stellen Sie sicher, Splashcreen Dateien zu Ihrem res/xml-Verzeichnis unter den entsprechenden Ordnern hinzuzufügen. Der zweite Parameter stellt dar, wie lange das Splashscreen in Millisekunden angezeigt werden. Es wird standardmäßig auf 3000 ms. Weitere Informationen finden Sie unter [Symbole und Splash-Screens](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). + +"SplashMaintainAspectRatio" Präferenz ist optional. Wenn wahr, Splash-Screen zeichenbaren nicht gestreckt wird, um den Bildschirm passen, sondern stattdessen einfach "" den Bildschirm, wie CSS abdeckt "Hintergrund-Größe: Schutz vor". Dies ist sehr nützlich, wenn Splash-Bildschirm Bilder können nicht, in keiner Weise, zum Beispiel verzerrt werden wenn sie Landschaft oder Text enthalten. Diese Einstellung funktioniert am besten mit Bildern, die große Margen (sichere Bereiche) haben, die sicher auf Bildschirme mit unterschiedlichen Seitenverhältnissen zugeschnitten werden können. + +Das Plugin lädt platsch zeichenbaren wenn Ausrichtung ändert, sodass Sie verschiedene Drawables für hoch- und Querformat Ausrichtungen angeben können. + +### Browser-Eigenheiten + +In Ihrem `"config.xml"`können Sie die folgenden Einstellungen: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS Macken + + * `FadeSplashScreen` (Boolean, standardmäßig auf `true festgelegt`): um zu verhindern, dass den Begrüßungsbildschirm ein-und ausblenden bei ihrer Anzeige Statusänderungen auf `false` festgelegt. + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration` (float, Standardwert ist `2`): gibt die Anzahl der Sekunden für den Begrüßungsbildschirm fade Effekt ausgeführt. + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner` (Boolean, standardmäßig auf `true festgelegt`): auf `false` festgelegt wird, um den Begrüßungsbildschirm Spinner auszublenden. + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## SplashScreen.Hide + +Schließen Sie den Splash-Screen. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Eigenarten + +Die Datei `config.xml` `AutoHideSplashScreen` Einstellung muss `false` sein. Verstecken des Begrüßungsbildschirms für zwei Sekunden Verzögerung, fügen Sie einen Timer wie die folgende in der `deviceready`-Ereignishandler: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## SplashScreen.Show + +Zeigt den Begrüßungsbildschirm. + + navigator.splashscreen.show(); + + +Ihre Anwendung kann nicht `navigator.splashscreen.show()` aufrufen, bis die app begonnen hat und das `deviceready`-Ereignis ausgelöst hat. Aber da in der Regel der Splash-Screen soll sichtbar sein, bevor die Anwendung gestartet wurde, scheint die Niederlage der Zweck des Begrüßungsbildschirms. Somit einige Konfiguration in der Datei `config.xml` werden automatisch die Splash `show` sofort nach Ihrer app-Start und Bildschirm bevor es voll begonnen hat, und das `deviceready`-Ereignis empfangen. Weitere Informationen zu dieser Konfiguration finden Sie unter [Symbole und Splash-Screens](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). Aus diesem Grund ist es unwahrscheinlich, dass Sie `navigator.splashscreen.show()` damit den Splash-Screen sichtbar ist für app-Start aufrufen müssen.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/de/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/de/index.md new file mode 100644 index 00000000..b9fc40d2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/de/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +Dieses Plugin zeigt und verbirgt einen Splash-Screen beim Start der Anwendung. + +## Installation + + cordova plugin add cordova-plugin-splashscreen + + +## Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Windows Phone 7 und 8 +* Windows 8 + +## Methoden + +* SplashScreen.Show +* SplashScreen.Hide + +### Android Eigenarten + +Sie müssen in der config.xml folgende Einstellungen vornehmen: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +Wo Foo ist der Name der Datei Splashscreen, vorzugsweise eine 9-Patch-Datei. Stellen Sie sicher, Splashcreen Dateien zu Ihrem res/xml-Verzeichnis unter den entsprechenden Ordnern hinzuzufügen. Der zweite Parameter stellt dar, wie lange das Splashscreen in Millisekunden angezeigt werden. Es wird standardmäßig auf 3000 ms. Weitere Informationen finden Sie unter [Symbole und Splash-Screens][1]. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## SplashScreen.Hide + +Schließen Sie den Splash-Screen. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Eigenarten + +Die Datei `config.xml` `AutoHideSplashScreen` Einstellung muss `false` sein. Verstecken des Begrüßungsbildschirms für zwei Sekunden Verzögerung, fügen Sie einen Timer wie die folgende in der `deviceready`-Ereignishandler: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## SplashScreen.Show + +Zeigt den Begrüßungsbildschirm. + + navigator.splashscreen.show(); + + +Ihre Anwendung kann nicht `navigator.splashscreen.show()` aufrufen, bis die app begonnen hat und das `deviceready`-Ereignis ausgelöst hat. Aber da in der Regel der Splash-Screen soll sichtbar sein, bevor die Anwendung gestartet wurde, scheint die Niederlage der Zweck des Begrüßungsbildschirms. Somit einige Konfiguration in der Datei `config.xml` werden automatisch die Splash `show` sofort nach Ihrer app-Start und Bildschirm bevor es voll begonnen hat, und das `deviceready`-Ereignis empfangen. Weitere Informationen zu dieser Konfiguration finden Sie unter [Symbole und Splash-Screens][1]. Aus diesem Grund ist es unwahrscheinlich, dass Sie `navigator.splashscreen.show()` damit den Splash-Screen sichtbar ist für app-Start aufrufen müssen. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/es/README.md new file mode 100644 index 00000000..1a94161a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/es/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +Este plugin muestra y esconde una pantalla de bienvenida durante el inicio de la aplicación. + +## Instalación + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * iOS + * Windows Phone 7 y 8 + * Windows 8 + * Windows + * Explorador + +## Métodos + + * splashscreen.show + * splashscreen.hide + +### Rarezas Android + +En el `archivo config.xml`, es necesario agregar las siguientes preferencias: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +Donde foo es el nombre del archivo splashscreen, preferiblemente un archivo de 9 parche. Asegúrese de agregar tus archivos splashcreen en tu directorio res/xml bajo las carpetas apropiadas. El segundo parámetro representa cuánto aparecerán el splashscreen en milisegundos. Valor predeterminado es ms 3000. Ver [los iconos y salpicadura pantallas](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) para obtener más información. + +Preferencia "SplashMaintainAspectRatio" es opcional. Si establece en true, pantalla dibujable no es estirado para caber la pantalla, pero en su lugar simplemente "cover" la pantalla, como CSS "background-size: cover". Esto es muy útil cuando las imágenes de pantallas splash no distorsionadas de cualquier manera, por ejemplo cuando contienen texto o paisaje. Esta opción funciona mejor con imágenes que tienen bordes grandes (zonas seguras) que pueden ser recortadas con seguridad en pantallas con diferentes relaciones de aspecto. + +El plugin recarga splash dibujable cuando cambia de orientación, por lo que puede especificar diferente dibujo para orientaciones vertical y horizontal. + +### Navegador rarezas + +Puede utilizar las siguientes preferencias en el `archivo config.xml`: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS rarezas + + * `FadeSplashScreen` (booleano, por defecto `true`): establecida en `false` para evitar que la pantalla de bienvenida de descolorarse adentro y hacia fuera cuando cambia su estado de presentación. + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration` (float, por defecto es `2`): especifica el número de segundos para que la pantalla se descolora efecto para ejecutar. + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner` (booleano, por defecto `true`): establecida en `false` para ocultar la ruleta de la pantalla de bienvenida. + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.hide + +Despedir a la pantalla de bienvenida. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +El `config.xml` del archivo `AutoHideSplashScreen` la configuración debe ser `false` . Para retrasar oculta la pantalla splash durante dos segundos, agregue un temporizador como la siguiente en el `deviceready` controlador de eventos: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +Muestra la pantalla de bienvenida. + + navigator.splashscreen.show(); + + +La aplicación no se puede llamar `navigator.splashscreen.show()` hasta que haya iniciado la aplicación y el `deviceready` evento ha despedido. Pero puesto que normalmente la pantalla está destinada a ser visible antes de que comience su aplicación, que parecerÃa que el propósito de la pantalla de bienvenida. Proporcionar cierta configuración en `config.xml` automáticamente `show` la pantalla de presentación inmediatamente después de su lanzamiento de la aplicación y antes de ser completamente ha iniciado y recibió el `deviceready` evento. Ver [los iconos y salpicadura pantallas](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) para obtener más información sobre haciendo esta configuración. Por esta razón, es poco probable que necesitas llamar a `navigator.splashscreen.show()` para hacer la pantalla visible para el inicio de la aplicación.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/es/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/es/index.md new file mode 100644 index 00000000..3295c27f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/es/index.md @@ -0,0 +1,76 @@ +<!--- + 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-plugin-splashscreen + +Este plugin muestra y esconde una pantalla de bienvenida durante el inicio de la aplicación. + +## Instalación + + cordova plugin add cordova-plugin-splashscreen + + +## Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* iOS +* Windows Phone 7 y 8 +* Windows 8 + +## Métodos + +* splashscreen.show +* splashscreen.hide + +### Rarezas Android + +En el archivo config.xml, tienes que añadir las siguientes preferencias: + + < nombre de preferencia = "SplashScreen" value = "foo" / >< nombre de preferencia = "SplashScreenDelay" value = "10000" / > + + +Donde foo es el nombre del archivo splashscreen, preferiblemente un archivo de 9 parche. Asegúrese de agregar tus archivos splashcreen en tu directorio res/xml bajo las carpetas apropiadas. El segundo parámetro representa cuánto aparecerán el splashscreen en milisegundos. Valor predeterminado es ms 3000. Ver [los iconos y salpicadura pantallas][1] para obtener más información. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.hide + +Despedir a la pantalla de bienvenida. + + Navigator.SplashScreen.Hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +El `config.xml` del archivo `AutoHideSplashScreen` la configuración debe ser `false` . Para retrasar oculta la pantalla splash durante dos segundos, agregue un temporizador como la siguiente en el `deviceready` controlador de eventos: + + setTimeout(function() {navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +Muestra la pantalla de bienvenida. + + Navigator.SplashScreen.Show(); + + +La aplicación no se puede llamar `navigator.splashscreen.show()` hasta que haya iniciado la aplicación y el `deviceready` evento ha despedido. Pero puesto que normalmente la pantalla está destinada a ser visible antes de que comience su aplicación, que parecerÃa que el propósito de la pantalla de bienvenida. Proporcionar cierta configuración en `config.xml` automáticamente `show` la pantalla de presentación inmediatamente después de su lanzamiento de la aplicación y antes de ser completamente ha iniciado y recibió el `deviceready` evento. Ver [los iconos y salpicadura pantallas][1] para obtener más información sobre haciendo esta configuración. Por esta razón, es poco probable que necesitas llamar a `navigator.splashscreen.show()` para hacer la pantalla visible para el inicio de la aplicación. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/fr/README.md new file mode 100644 index 00000000..65f58803 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/fr/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +Ce plugin affiche et masque un écran de démarrage lors du lancement de l'application. + +## Installation + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * iOS + * Windows Phone 7 et 8 + * Windows 8 + * Windows + * Navigateur + +## Méthodes + + * splashscreen.Show + * splashscreen.Hide + +### Quirks Android + +Dans votre `fichier config.xml`, vous devez ajouter les préférences suivantes : + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +Où foo est le nom du fichier splashscreen, préférablement un fichier de 9 correctif. Assurez-vous d'ajouter vos fichiers splashcreen dans votre répertoire res/xml dans les dossiers appropriés. Le deuxième paramètre représente combien de temps le splashscreen apparaîtra en millisecondes. Il est par défaut à 3000 ms. Pour plus d'informations, consultez [icônes et écrans de démarrage](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). + +Préférence de « SplashMaintainAspectRatio » est facultative. Si défini à true, écran de démarrage drawable n'est pas étirée pour s'adapter écran, mais plutôt simplement « couvre » l'écran, comme CSS "fond-taille : couverture". Ceci est très utile lorsque images écran de démarrage ne peut pas être déformées en quelque sorte, par exemple lorsqu'ils contiennent des décors ou texte. Ce paramètre fonctionne mieux avec des images qui ont des marges importantes (zones de sécurité) qui peuvent être recadrées en toute sécurité sur les écrans avec des proportions différentes. + +Le plugin recharge splash drawable chaque fois que l'orientation change, donc vous pouvez spécifier différents drawables pour les orientations portrait et paysage. + +### Bizarreries navigateur + +Vous pouvez utiliser les préférences suivantes dans votre `fichier config.xml`: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### Notes au sujet d'iOS + + * `FadeSplashScreen` (boolean, par défaut est `true`): la valeur `false` pour empêcher l'écran de démarrage de fading in et out lorsque son état d'affichage est modifié. + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration` (float, la valeur par défaut `2`): spécifie le nombre de secondes que l'écran de démarrage s'estomper l'effet d'exécuter. + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner` (boolean, par défaut est `true`): la valeur `false` pour masquer le cône de l'écran de démarrage. + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.Hide + +Faire disparaître de l'écran de démarrage. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +Paramètre `AutoHideSplashScreen` du fichier `config.xml` doit avoir la valeur `false`. Pour retarder la cacher l'écran de démarrage pendant deux secondes, ajouter un minuteur semblable à la suivante dans le gestionnaire d'événements `deviceready` : + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.Show + +Affiche l'écran de démarrage. + + navigator.splashscreen.show(); + + +Votre application ne peut pas appeler `navigator.splashscreen.show()` jusqu'à ce que l'application a commencé et l'événement `deviceready` est déclenché. Mais puisqu'en général, l'écran de démarrage est destiné à être visible avant que votre application a commencé, qui semblerait à l'encontre des objectifs de l'écran de démarrage. Fournir une configuration dans le fichier `config.xml` automatiquement `show` le splash projettera immédiatement après votre lancement de l'app et avant qu'il a complètement démarré et a reçu l'événement `deviceready`. Voir les [icônes et les écrans de démarrage](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) pour plus d'informations sur la conduite de cette configuration. Pour cette raison, il est peu probable que vous devez appeler `navigator.splashscreen.show()` pour rendre l'écran de démarrage visible pour le démarrage de l'application.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/fr/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/fr/index.md new file mode 100644 index 00000000..6d2fd088 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/fr/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +Ce plugin affiche et masque un écran de démarrage lors du lancement de l'application. + +## Installation + + cordova plugin add cordova-plugin-splashscreen + + +## Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Windows Phone 7 et 8 +* Windows 8 + +## Méthodes + +* splashscreen.Show +* splashscreen.Hide + +### Quirks Android + +Dans votre fichier config.xml, vous devez ajouter les préférences suivantes : + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +Où foo est le nom du fichier splashscreen, préférablement un fichier de 9 correctif. Assurez-vous d'ajouter vos fichiers splashcreen dans votre répertoire res/xml dans les dossiers appropriés. Le deuxième paramètre représente combien de temps le splashscreen apparaîtra en millisecondes. Il est par défaut à 3000 ms. Pour plus d'informations, consultez [icônes et écrans de démarrage][1]. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.Hide + +Faire disparaître de l'écran de démarrage. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +Paramètre `AutoHideSplashScreen` du fichier `config.xml` doit avoir la valeur `false`. Pour retarder la cacher l'écran de démarrage pendant deux secondes, ajouter un minuteur semblable à la suivante dans le gestionnaire d'événements `deviceready` : + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.Show + +Affiche l'écran de démarrage. + + navigator.splashscreen.show(); + + +Votre application ne peut pas appeler `navigator.splashscreen.show()` jusqu'à ce que l'application a commencé et l'événement `deviceready` est déclenché. Mais puisqu'en général, l'écran de démarrage est destiné à être visible avant que votre application a commencé, qui semblerait à l'encontre des objectifs de l'écran de démarrage. Fournir une configuration dans le fichier `config.xml` automatiquement `show` le splash projettera immédiatement après votre lancement de l'app et avant qu'il a complètement démarré et a reçu l'événement `deviceready`. Voir les [icônes et les écrans de démarrage][1] pour plus d'informations sur la conduite de cette configuration. Pour cette raison, il est peu probable que vous devez appeler `navigator.splashscreen.show()` pour rendre l'écran de démarrage visible pour le démarrage de l'application. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/it/README.md new file mode 100644 index 00000000..2a6c6ba4 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/it/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +Questo plugin Visualizza e nasconde una schermata iniziale durante l'avvio dell'applicazione. + +## Installazione + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * iOS + * Windows Phone 7 e 8 + * Windows 8 + * Windows + * Browser + +## Metodi + + * splashscreen + * splashscreen.Hide + +### Stranezze Android + +Nel vostro `config. XML`, è necessario aggiungere le seguenti preferenze: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +Dove foo è il nome del file splashscreen, preferibilmente un file 9 patch. Assicurati di aggiungere i tuoi file splashcreen res/xml nella directory sotto cartelle appropriate. Il secondo parametro rappresenta quanto tempo lo splashscreen apparirà in millisecondi. Il valore predefinito è 3000 ms. Per ulteriori informazioni, vedere [icone e schermate iniziali](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). + +"SplashMaintainAspectRatio" preferenza è facoltativo. Se impostato su true, schermata iniziale drawable non viene adattata per misura lo schermo, ma invece semplicemente "copre" lo schermo, come CSS "sfondo-dimensione: copertina". Questo è molto utile quando immagini schermata iniziale non possono essere distorta in qualche modo, per esempio quando contengono testo o scenario. Questa impostazione funziona meglio con immagini che hanno grandi margini (zone sicure) che possono essere ritagliati in modo sicuro su schermi con proporzioni diverse. + +Il plugin viene ricaricata splash drawable ogni volta che cambia orientamento, è possibile specificare diversi parte per orientamento verticale e orizzontale. + +### Stranezze browser + +Nel vostro `config. XML`, è possibile utilizzare le seguenti preferenze: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS stranezze + + * `FadeSplashScreen` (boolean, impostazioni predefinite a `true`): impostare su `false` per impedire che la schermata iniziale e scompaiono quando cambia il relativo stato di visualizzazione. + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration` (float, il valore predefinito è `2`): specifica il numero di secondi per la schermata iniziale dissolvenza effetto da eseguire. + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner` (boolean, impostazioni predefinite a `true`): impostare su `false` per nascondere la filatrice schermata iniziale. + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.Hide + +Respingere la schermata iniziale. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +Impostazione `AutoHideSplashScreen` del file `config.xml` deve essere `false`. Per ritardare nascondendo la schermata iniziale per due secondi, aggiungere un timer ad esempio nel gestore eventi `deviceready`: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen + +Visualizza la schermata iniziale. + + navigator.splashscreen.show(); + + +L'applicazione non può chiamare `navigator.splashscreen.show()` fino a quando l'app ha iniziato e ha generato l'evento `deviceready`. Ma poiché in genere la schermata iniziale è destinata ad essere visibile prima app ha iniziato, che sembrerebbe per sconfiggere lo scopo della schermata iniziale. Fornendo qualche configurazione nel `file config.xml` sarà automaticamente `show` il tonfo schermo subito dopo il lancio dell'app e prima che completamente ha iniziato e ha ricevuto l'evento `deviceready`. Per ulteriori informazioni su facendo questa configurazione, vedere [icone e schermate iniziali](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). Per questo motivo, è improbabile che dovete chiamare `navigator.splashscreen.show()` per rendere la schermata visibile per avvio di app.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/it/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/it/index.md new file mode 100644 index 00000000..70435415 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/it/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +Questo plugin Visualizza e nasconde una schermata iniziale durante l'avvio dell'applicazione. + +## Installazione + + cordova plugin add cordova-plugin-splashscreen + + +## Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* iOS +* Windows Phone 7 e 8 +* Windows 8 + +## Metodi + +* splashscreen +* splashscreen.Hide + +### Stranezze Android + +Nel vostro config. xml, è necessario aggiungere le seguenti preferenze: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +Dove foo è il nome del file splashscreen, preferibilmente un file 9 patch. Assicurati di aggiungere i tuoi file splashcreen res/xml nella directory sotto cartelle appropriate. Il secondo parametro rappresenta quanto tempo lo splashscreen apparirà in millisecondi. Il valore predefinito è 3000 ms. Per ulteriori informazioni, vedere [icone e schermate iniziali][1]. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.Hide + +Respingere la schermata iniziale. + + navigator.splashscreen.hide(); + + +### BlackBerry 10, WP8, iOS Quirk + +Impostazione `AutoHideSplashScreen` del file `config.xml` deve essere `false`. Per ritardare nascondendo la schermata iniziale per due secondi, aggiungere un timer ad esempio nel gestore eventi `deviceready`: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen + +Visualizza la schermata iniziale. + + navigator.splashscreen.show(); + + +L'applicazione non può chiamare `navigator.splashscreen.show()` fino a quando l'app ha iniziato e ha generato l'evento `deviceready`. Ma poiché in genere la schermata iniziale è destinata ad essere visibile prima app ha iniziato, che sembrerebbe per sconfiggere lo scopo della schermata iniziale. Fornendo qualche configurazione nel `file config.xml` sarà automaticamente `show` il tonfo schermo subito dopo il lancio dell'app e prima che completamente ha iniziato e ha ricevuto l'evento `deviceready`. Per ulteriori informazioni su facendo questa configurazione, vedere [icone e schermate iniziali][1]. Per questo motivo, è improbabile che dovete chiamare `navigator.splashscreen.show()` per rendere la schermata visibile per avvio di app. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ja/README.md new file mode 100644 index 00000000..a688b279 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ja/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +ã“ã®ãƒ—ラグインãŒè¡¨ç¤ºã•れã€ã‚¢ãƒ—リケーションã®èµ·å‹•ä¸ã«ã‚¹ãƒ—ラッシュ スクリーンをéžè¡¨ç¤ºã«ã—ã¾ã™ã€‚ + +## インストール + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ + * ã‚¢ãƒžã‚¾ãƒ³ç« OS + * アンドãƒã‚¤ãƒ‰ + * ブラックベリー 10 + * iOS + * Windows Phone 7 㨠8 + * Windows 8 + * Windows + * ブラウザー + +## メソッド + + * splashscreen.show + * splashscreen.hide + +### Android ã®ç™– + +ã‚ãªãŸã®`config.xml`å†…ã®æ¬¡ã®è¨å®šã‚’è¿½åŠ ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚ + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +Foo ãŒã§ãれ㰠9 パッãƒãƒ•ァイル splashscreen ファイルã®åå‰ã§ã™ã€‚ è§£åƒåº¦/xml ディレクトリã®é©åˆ‡ãªãƒ•ォルダーã®ä¸‹ã« splashcreen ãƒ•ã‚¡ã‚¤ãƒ«ã‚’è¿½åŠ ã™ã‚‹ã“ã¨ã‚’確èªã—ã¾ã™ã€‚ 2 番目ã®ãƒ‘ラメーターã¯ã€ã‚¹ãƒ—ラッシュ ・ スクリーンãŒã®è¡¨ç¤ºæ™‚é–“ (ミリ秒å˜ä½) を表ã—ã¾ã™ã€‚ デフォルトã§ã¯ 3000 ミリ秒ã§ã™ã€‚ 詳細ã«ã¤ã„ã¦ã¯ã€[アイコンã¨ã‚¹ãƒ—ラッシュ画é¢](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) ã‚’å‚ç…§ã—ã¦ãã ã•ã„。 + +"SplashMaintainAspectRatio"ã®è¨å®šã¯ã‚ªãƒ—ションã§ã™ã€‚ True ã®å ´åˆã€ã‚¹ãƒ—ãƒ©ãƒƒã‚·ãƒ¥ç”»é¢æç”»ã«è¨å®šç”»é¢ã‚’埋ã‚ã‚‹ãŸã‚ã«æ‹¡å¤§ã•れã¾ã›ã‚“ãŒã€ä»£ã‚りã«å˜ã«ã€Œã‚«ãƒãƒ¼ã€ç”»é¢ã§ã¯ã€CSS ã®ã‚ˆã†ãªå ´åˆã€ŒèƒŒæ™¯-サイズ: ã‚«ãƒãƒ¼ã€. ã“れã¯ã€ãŸã¨ãˆã°é¢¨æ™¯ã¾ãŸã¯ãƒ†ã‚ストãŒå«ã¾ã‚Œã¦ã„ã‚‹å ´åˆã€ä»»æ„ã®æ–¹æ³•ã§ã‚¹ãƒ—ラッシュ画é¢ç”»åƒãŒæªã‚€ã“ã¨ãŒã§ããªã„éžå¸¸ã«ä¾¿åˆ©ã§ã™ã€‚ ã“ã®è¨å®šã¯ã€ç”»é¢ã¨ç•°ãªã‚‹ç¸¦æ¨ªæ¯”ã§å®‰å…¨ã«ãƒˆãƒªãƒŸãƒ³ã‚°ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™å¤§è¦æ¨¡ãªãƒžãƒ¼ã‚¸ãƒ³ (安全ãªåœ°åŸŸ) ã®ç”»åƒã«é©ã—ã¦ã„ã¾ã™ã€‚ + +ç¸¦é•·ã¨æ¨ªé•·ã®ç•°ãªã‚‹ãƒ‰ãƒã‚¦ã‚¢ãƒ–ルを指定ã§ãるよã†ã«ã€ãƒ—ラグインã¯å‘ãを変更ã™ã‚‹ãŸã³ã«ã‚¹ãƒ—ラッシュ ドãƒã‚¦ã‚¢ãƒ–ルをリãƒãƒ¼ãƒ‰ã—ã¾ã™ã€‚ + +### ブラウザーã®ç™– + +ã‚ãªãŸã®`config.xml`ã§æ¬¡ã®è¨å®šã‚’使用ã§ãã¾ã™ã€‚ + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS ã®ç™– + + * `FadeSplashScreen`(ãƒ–ãƒ¼ãƒ«å€¤ã€æ—¢å®šã§ [ `true`): スプラッシュ画é¢ãŒãƒ•ェードインã¨ãƒ•ェードアウトã®è¡¨ç¤ºçŠ¶æ…‹ãŒå¤‰æ›´ã•れãŸã¨ãã™ã‚‹ã“ã¨ã‚’防ããŸã‚ã«`false`ã«è¨å®šã—ã¾ã™ã€‚ + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration`(float, デフォルトã¯`2`): スプラッシュ画é¢ã®ç§’æ•°ã®ãƒ•ェードを実行ã™ã‚‹åŠ¹æžœã‚’æŒ‡å®šã—ã¾ã™ã€‚ + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner`(ãƒ–ãƒ¼ãƒ«å€¤ã€æ—¢å®šã§ [ `true`): スプラッシュ スクリーン スピナーをéžè¡¨ç¤ºã«ã™ã‚‹ã‚’`false`ã«è¨å®šã—ã¾ã™ã€‚ + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.hide + +スプラッシュ スクリーンを閉ã˜ã¾ã™ã€‚ + + navigator.splashscreen.hide(); + + +### ブラックベリー 10ã€WP8ã€iOS ã®æ°—ã¾ãれ + +`config.xml` ファイル㮠`AutoHideSplashScreen` ã®è¨å®šã¯ `false` ã§ã‚ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚ é…å»¶ã‚’ 2 秒間スプラッシュ スクリーンをéžè¡¨ç¤ºã« `deviceready` イベント ãƒãƒ³ãƒ‰ãƒ©ãƒ¼ã§ã€æ¬¡ã®ã‚ˆã†ã‚¿ã‚¤ãƒžãƒ¼ã‚’è¿½åŠ ã—ã¾ã™ã€‚ + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +スプラッシュ画é¢ãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + + navigator.splashscreen.show(); + + +アプリãŒé–‹å§‹ã•れã€`deviceready` イベントãŒç™ºç”Ÿã™ã‚‹ã¾ã§ã€ã‚¢ãƒ—リケーション㯠`navigator.splashscreen.show()` を呼ã³å‡ºã™ã“ã¨ã¯ã§ãã¾ã›ã‚“。 ã—ã‹ã—ã€ä»¥æ¥ã€é€šå¸¸ã‚¹ãƒ—ラッシュ画é¢ã‚¢ãƒ—リ開始å‰ã«è¡¨ç¤ºã™ã‚‹ã‚‚ã®ã§ã™ã¨æ€ã‚れるã€ã‚¹ãƒ—ラッシュ スクリーンã®ç›®çš„ã®æ•—北ã—ã¾ã™ã€‚ `config.xml` ã«ã„ãã¤ã‹ã®æ§‹æˆã‚’æä¾›ã™ã‚‹ã¯è‡ªå‹•的㫠`表示` スプラッシュ画é¢ã€ã‚¢ãƒ—リを起動後ã™ãã«ã€ãれãŒå®Œå…¨ã«èµ·å‹•ã—ã€`deviceready` イベントをå—ä¿¡ã™ã‚‹å‰ã«ã€‚ 詳細ã«ã¤ã„ã¦ã¯ã“ã®æ§‹æˆã‚’行ã†ã«ã¯ã€[アイコンã¨ã‚¹ãƒ—ラッシュ画é¢](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) ã‚’å‚ç…§ã—ã¦ãã ã•ã„。 ã“ã®ç†ç”±ã®ãŸã‚ã«ã‚¢ãƒ—リ起動時ã®ã‚¹ãƒ—ラッシュ ã‚¹ã‚¯ãƒªãƒ¼ãƒ³ã‚’ç¢ºèª `navigator.splashscreen.show()` をコールã™ã‚‹å¿…è¦ãŒã‚ã‚‹å¯èƒ½æ€§ãŒé«˜ã„ã§ã™ã€‚
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ja/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ja/index.md new file mode 100644 index 00000000..24e72e5a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ja/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +ã“ã®ãƒ—ラグインãŒè¡¨ç¤ºã•れã€ã‚¢ãƒ—リケーションã®èµ·å‹•ä¸ã«ã‚¹ãƒ—ラッシュ スクリーンをéžè¡¨ç¤ºã«ã—ã¾ã™ã€‚ + +## インストール + + cordova plugin add cordova-plugin-splashscreen + + +## サãƒãƒ¼ãƒˆã•れã¦ã„るプラットフォーム+ +* ã‚¢ãƒžã‚¾ãƒ³ç« OS +* アンドãƒã‚¤ãƒ‰ +* ブラックベリー 10 +* iOS +* Windows Phone 7 㨠8 +* Windows 8 + +## メソッド + +* splashscreen.show +* splashscreen.hide + +### Android ã®ç™– + +ã‚ãªãŸã® config.xml を以下ã®è¨å®šã‚’è¿½åŠ ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚ + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +Foo ãŒã§ãれ㰠9 パッãƒãƒ•ァイル splashscreen ファイルã®åå‰ã§ã™ã€‚ è§£åƒåº¦/xml ディレクトリã®é©åˆ‡ãªãƒ•ォルダーã®ä¸‹ã« splashcreen ãƒ•ã‚¡ã‚¤ãƒ«ã‚’è¿½åŠ ã™ã‚‹ã“ã¨ã‚’確èªã—ã¾ã™ã€‚ 2 番目ã®ãƒ‘ラメーターã¯ã€ã‚¹ãƒ—ラッシュ ・ スクリーンãŒã®è¡¨ç¤ºæ™‚é–“ (ミリ秒å˜ä½) を表ã—ã¾ã™ã€‚ デフォルトã§ã¯ 3000 ミリ秒ã§ã™ã€‚ 詳細ã«ã¤ã„ã¦ã¯ã€[アイコンã¨ã‚¹ãƒ—ラッシュ画é¢][1] ã‚’å‚ç…§ã—ã¦ãã ã•ã„。 + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.hide + +スプラッシュ スクリーンを閉ã˜ã¾ã™ã€‚ + + navigator.splashscreen.hide(); + + +### ブラックベリー 10ã€WP8ã€iOS ã®æ°—ã¾ãれ + +`config.xml` ファイル㮠`AutoHideSplashScreen` ã®è¨å®šã¯ `false` ã§ã‚ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚ é…å»¶ã‚’ 2 秒間スプラッシュ スクリーンをéžè¡¨ç¤ºã« `deviceready` イベント ãƒãƒ³ãƒ‰ãƒ©ãƒ¼ã§ã€æ¬¡ã®ã‚ˆã†ã‚¿ã‚¤ãƒžãƒ¼ã‚’è¿½åŠ ã—ã¾ã™ã€‚ + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +スプラッシュ画é¢ãŒè¡¨ç¤ºã•れã¾ã™ã€‚ + + navigator.splashscreen.show(); + + +アプリãŒé–‹å§‹ã•れã€`deviceready` イベントãŒç™ºç”Ÿã™ã‚‹ã¾ã§ã€ã‚¢ãƒ—リケーション㯠`navigator.splashscreen.show()` を呼ã³å‡ºã™ã“ã¨ã¯ã§ãã¾ã›ã‚“。 ã—ã‹ã—ã€ä»¥æ¥ã€é€šå¸¸ã‚¹ãƒ—ラッシュ画é¢ã‚¢ãƒ—リ開始å‰ã«è¡¨ç¤ºã™ã‚‹ã‚‚ã®ã§ã™ã¨æ€ã‚れるã€ã‚¹ãƒ—ラッシュ スクリーンã®ç›®çš„ã®æ•—北ã—ã¾ã™ã€‚ `config.xml` ã«ã„ãã¤ã‹ã®æ§‹æˆã‚’æä¾›ã™ã‚‹ã¯è‡ªå‹•的㫠`表示` スプラッシュ画é¢ã€ã‚¢ãƒ—リを起動後ã™ãã«ã€ãれãŒå®Œå…¨ã«èµ·å‹•ã—ã€`deviceready` イベントをå—ä¿¡ã™ã‚‹å‰ã«ã€‚ 詳細ã«ã¤ã„ã¦ã¯ã“ã®æ§‹æˆã‚’行ã†ã«ã¯ã€[アイコンã¨ã‚¹ãƒ—ラッシュ画é¢][1] ã‚’å‚ç…§ã—ã¦ãã ã•ã„。 ã“ã®ç†ç”±ã®ãŸã‚ã«ã‚¢ãƒ—リ起動時ã®ã‚¹ãƒ—ラッシュ ã‚¹ã‚¯ãƒªãƒ¼ãƒ³ã‚’ç¢ºèª `navigator.splashscreen.show()` をコールã™ã‚‹å¿…è¦ãŒã‚ã‚‹å¯èƒ½æ€§ãŒé«˜ã„ã§ã™ã€‚ diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ko/README.md new file mode 100644 index 00000000..5e10d207 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ko/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +ì´ í”ŒëŸ¬ê·¸ì¸ì€ 표시 하 ê³ ì‘ìš© 프로그램 실행 하는 ë™ì•ˆ 시작 í™”ë©´ì„ ìˆ¨ê¹ë‹ˆë‹¤. + +## 설치 + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## ì§€ì› ë˜ëŠ” í”Œëž«í¼ + + * 아마존 화재 ìš´ì˜ ì²´ì œ + * 안 드 로ì´ë“œ + * ë¸”ëž™ë² ë¦¬ 10 + * iOS + * Windows Phone 7ê³¼ 8 + * 윈ë„ìš° 8 + * 윈ë„ìš° + * 브ë¼ìš°ì € + +## 메서드 + + * splashscreen.show + * splashscreen.hide + +### 안 드 로ì´ë“œ 단ì + +`Config.xml`ì— ë‹¤ìŒ í™˜ê²½ ì„¤ì •ì— ì¶”ê°€ 해야 합니다. + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +여기서 foo splashscreen 파ì¼, ì„ í˜¸ 9 패치 파ì¼ì˜ ì´ë¦„입니다. ì ì ˆ 한 í´ë” 아래 res/xml ë””ë ‰í† ë¦¬ì— splashcreen 파ì¼ì„ 추가 해야 합니다. ë‘ ë²ˆì§¸ 매개 변수는 splashscreen 얼마나 밀리초 단위로 표시 ë©ë‹ˆë‹¤ 나타냅니다. 3000 ms 기본값으로 사용 ë©ë‹ˆë‹¤. ìžì„¸í•œ ë‚´ìš©ì€ [ì•„ì´ì½˜ ë° ì‹œìž‘ 화면ì„](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) 참조 하ì‹ì‹œì˜¤. + +"SplashMaintainAspectRatio" ì·¨í–¥ì€ ì„ íƒ ì‚¬í•입니다. Drawable, 시작 화면 ì„¤ì • í™”ë©´ì— ë§žê²Œ 확장 ë˜ì§€ 하지만 ëŒ€ì‹ ë‹¨ìˆœížˆ "커버" CSS ê°™ì€ í™”ë©´ "ë°°ê²½-í¬ê¸°: ë®ê°œ". 시작 화면 ì´ë¯¸ì§€ 예: í’ê²½ ë˜ëŠ” í…스트를 í¬í•¨ 하는 경우 ì–´ë–¤ ì‹ìœ¼ë¡œë“ ì—서 왜곡 ë 수 없는 ê²½ìš°ì— ë§¤ìš° ìœ ìš© 합니다. ì´ ì„¤ì •ì€ í° ì—¬ë°± (ì•ˆì „ ì§€ì—) ì•ˆì „ 하 게 다른 종횡비와 í™”ë©´ì— ìžë¥¼ 수 있는 ì´ë¯¸ì§€ì— 가장 ì í•© 합니다. + +í”ŒëŸ¬ê·¸ì¸ ë‹¤ì‹œ 로드 스플래시 drawable ë°©í–¥ì´ ë³€ê²½ ë 때마다 세로 ë° ê°€ë¡œ ë°©í–¥ì— ëŒ€ 한 다른 drawables를 ì§€ì •í• ìˆ˜ 있ë„ë¡ í•©ë‹ˆë‹¤. + +### 브ë¼ìš°ì € 만지면 + +`Config.xml`ì— ë‹¤ìŒ ê¸°ë³¸ ì„¤ì •ì„ ì‚¬ìš©í• ìˆ˜ 있습니다. + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS 단ì + + * `FadeSplashScreen` (부울 `true`로 기본값): 시작 화면 표시 ìƒíƒœë¡œ 변경 ë 때 밖으로 퇴색 하지 않ë„ë¡ í•˜ë ¤ë©´ `false` 로 ì„¤ì •. + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration` (ë¶€ë™, `2`기본값): 시작 í™”ë©´ì— ëŒ€ 한 ì´ˆ 페ì´ë“œ 효과를 실행 하는 ì§€ì • 합니다. + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner` (부울 `true`로 기본값): 스플래시 화면 íšŒì „ìžë¥¼ ìˆ¨ê¸°ë ¤ë©´ `false` 로 ì„¤ì •. + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.hide + +시작 í™”ë©´ì„ ë‹«ìŠµë‹ˆë‹¤. + + navigator.splashscreen.hide(); + + +### ë¸”ëž™ë² ë¦¬ 10, WP8, iOS 특질 + +`config.xml` 파ì¼ì˜ `AutoHideSplashScreen` ì„¤ì •ì„ `false` 여야 합니다. 2 ì´ˆ ë™ì•ˆ 시작 í™”ë©´ì„ ìˆ¨ê¸°ê³ ì§€ì—°, `deviceready` ì´ë²¤íЏ 처리기ì—서 다ìŒê³¼ ê°™ì€ íƒ€ì´ë¨¸ë¥¼ 추가: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +시작 í™”ë©´ì„ í‘œì‹œí•©ë‹ˆë‹¤. + + navigator.splashscreen.show(); + + +ì‘ìš© 프로그램 시작 ë° `deviceready` ì´ë²¤íŠ¸ëŠ” ë°œìƒ ë 때까지 ì‘ìš© í”„ë¡œê·¸ëž¨ì´ `navigator.splashscreen.show()`ì„ í˜¸ì¶œí• ìˆ˜ 없습니다. 하지만 ê·¸ 스플래시 스í¬ë¦°ì˜ 목ì 것 같다 ì¼ë°˜ì 으로 시작 í™”ë©´ì´ ë‹¹ì‹ ì˜ ì• í”Œ 리 ì¼€ì´ ì…˜ 시작 하기 ì „ì— í‘œì‹œ ë ìš´ëª…ì´ ë‹¤, ì´í›„. `config.xmlì—서` 몇 가지 êµ¬ì„±ì„ ì œê³µ 하 ìžë™ìœ¼ë¡œ 스플래시 `표시` 화면 ì• í”Œ 리 ì¼€ì´ ì…˜ 출시 ì§í›„와 ê·¸ê²ƒì€ ì™„ë²½ 하 게 시작 하 ê³ `deviceready` ì´ë²¤íŠ¸ë¥¼ ë°›ì€ ì „ì—. ì´ êµ¬ì„± 하 ê³ ìžì„¸í•œ ë‚´ìš©ì€ [ì•„ì´ì½˜ ë° ì‹œìž‘ 화면ì„](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html) 참조 하ì‹ì‹œì˜¤. ì´ëŸ¬í•œ ì´ìœ 로, ê·¸ê²ƒì€ ê°€ëŠ¥ì„±ì´ ì‹œìž‘ í™”ë©´ì€ ì‘ìš© 프로그램 ì‹œìž‘ì— ëŒ€ 한 표시 ë˜ë„ë¡ `navigator.splashscreen.show()`를 호출 해야입니다.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ko/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ko/index.md new file mode 100644 index 00000000..6a0ea989 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ko/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +ì´ í”ŒëŸ¬ê·¸ì¸ì€ 표시 하 ê³ ì‘ìš© 프로그램 실행 하는 ë™ì•ˆ 시작 í™”ë©´ì„ ìˆ¨ê¹ë‹ˆë‹¤. + +## 설치 + + cordova plugin add cordova-plugin-splashscreen + + +## ì§€ì› ë˜ëŠ” í”Œëž«í¼ + +* 아마존 화재 ìš´ì˜ ì²´ì œ +* 안 드 로ì´ë“œ +* ë¸”ëž™ë² ë¦¬ 10 +* iOS +* Windows Phone 7ê³¼ 8 +* 윈ë„ìš° 8 + +## 메서드 + +* splashscreen.show +* splashscreen.hide + +### 안 드 로ì´ë“œ 단ì + +ë‹¹ì‹ ì˜ config.xmlì— ë‹¤ìŒ í™˜ê²½ ì„¤ì •ì— ì¶”ê°€ 해야 합니다. + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +여기서 foo splashscreen 파ì¼, ì„ í˜¸ 9 패치 파ì¼ì˜ ì´ë¦„입니다. ì ì ˆ 한 í´ë” 아래 res/xml ë””ë ‰í† ë¦¬ì— splashcreen 파ì¼ì„ 추가 해야 합니다. ë‘ ë²ˆì§¸ 매개 변수는 splashscreen 얼마나 밀리초 단위로 표시 ë©ë‹ˆë‹¤ 나타냅니다. 3000 ms 기본값으로 사용 ë©ë‹ˆë‹¤. ìžì„¸í•œ ë‚´ìš©ì€ [ì•„ì´ì½˜ ë° ì‹œìž‘ 화면ì„][1] 참조 하ì‹ì‹œì˜¤. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.hide + +시작 í™”ë©´ì„ ë‹«ìŠµë‹ˆë‹¤. + + navigator.splashscreen.hide(); + + +### ë¸”ëž™ë² ë¦¬ 10, WP8, iOS 특질 + +`config.xml` 파ì¼ì˜ `AutoHideSplashScreen` ì„¤ì •ì„ `false` 여야 합니다. 2 ì´ˆ ë™ì•ˆ 시작 í™”ë©´ì„ ìˆ¨ê¸°ê³ ì§€ì—°, `deviceready` ì´ë²¤íЏ 처리기ì—서 다ìŒê³¼ ê°™ì€ íƒ€ì´ë¨¸ë¥¼ 추가: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +시작 í™”ë©´ì„ í‘œì‹œí•©ë‹ˆë‹¤. + + navigator.splashscreen.show(); + + +ì‘ìš© 프로그램 시작 ë° `deviceready` ì´ë²¤íŠ¸ëŠ” ë°œìƒ ë 때까지 ì‘ìš© í”„ë¡œê·¸ëž¨ì´ `navigator.splashscreen.show()`ì„ í˜¸ì¶œí• ìˆ˜ 없습니다. 하지만 ê·¸ 스플래시 스í¬ë¦°ì˜ 목ì 것 같다 ì¼ë°˜ì 으로 시작 í™”ë©´ì´ ë‹¹ì‹ ì˜ ì• í”Œ 리 ì¼€ì´ ì…˜ 시작 하기 ì „ì— í‘œì‹œ ë ìš´ëª…ì´ ë‹¤, ì´í›„. `config.xmlì—서` 몇 가지 êµ¬ì„±ì„ ì œê³µ 하 ìžë™ìœ¼ë¡œ 스플래시 `표시` 화면 ì• í”Œ 리 ì¼€ì´ ì…˜ 출시 ì§í›„와 ê·¸ê²ƒì€ ì™„ë²½ 하 게 시작 하 ê³ `deviceready` ì´ë²¤íŠ¸ë¥¼ ë°›ì€ ì „ì—. ì´ êµ¬ì„± 하 ê³ ìžì„¸í•œ ë‚´ìš©ì€ [ì•„ì´ì½˜ ë° ì‹œìž‘ 화면ì„][1] 참조 하ì‹ì‹œì˜¤. ì´ëŸ¬í•œ ì´ìœ 로, ê·¸ê²ƒì€ ê°€ëŠ¥ì„±ì´ ì‹œìž‘ í™”ë©´ì€ ì‘ìš© 프로그램 ì‹œìž‘ì— ëŒ€ 한 표시 ë˜ë„ë¡ `navigator.splashscreen.show()`를 호출 해야입니다. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/pl/README.md new file mode 100644 index 00000000..0156be56 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/pl/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +Ten plugin wyÅ›wietla i ukrywa ekran powitalny podczas uruchamiania aplikacji. + +## Instalacja + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## ObsÅ‚ugiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * iOS + * Windows Phone 7 i 8 + * Windows 8 + * Windows + * PrzeglÄ…darka + +## Metody + + * splashscreen.show + * splashscreen.Hide + +### Dziwactwa Androida + +W pliku `config.xml`musisz dodać nastÄ™pujÄ…ce preferencje: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +Gdzie foo jest nazwÄ… pliku ekranu powitalnego, najlepiej 9 Å‚atce. Upewnij siÄ™ dodać pliki splashcreen do katalogu res/xml w odpowiednich folderach. Drugi parametr reprezentuje, jak dÅ‚ugo ekranu powitalnego pojawi siÄ™ w milisekundach. DomyÅ›lnie 3000 ms. Aby uzyskać wiÄ™cej informacji, zobacz [ikony i ekrany powitalne w aplikacjach](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). + +"SplashMaintainAspectRatio" preferencji jest opcjonalne. JeÅ›li zestaw na wartość true, ekran powitalny dolarowe nie jest rozciÄ…gniÄ™ty do ekranów, ale zamiast po prostu "obejmuje" ekranu, jak CSS "tÅ‚o-rozmiar: okÅ‚adka". Jest to bardzo przydatne, kiedy opryskać tÄ™cza obrazy nie znieksztaÅ‚cony w jakikolwiek sposób, na przykÅ‚ad, gdy zawierajÄ… one dekoracje lub tekst. To ustawienie dziaÅ‚a najlepiej z obrazów, które majÄ… duże marginesy (bezpiecznych obszarów), które mogÄ… być bezpiecznie przyciÄ™te na ekrany z różnych proporcji. + +Plugin Å‚aduje rozchlapać dolarowe, gdy zmienia orientacjÄ™, tak można okreÅ›lić różnych drawables do orientacji pionowej i poziomej. + +### Quirks przeglÄ…darki + +W pliku `config.xml`można użyć nastÄ™pujÄ…ce preferencje: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### Dziwactwa iOS + + * `FadeSplashScreen` (wartość logiczna, domyÅ›lnie `true`): zestaw na `false` , aby zapobiec ZnikajÄ…ca i odkÅ‚adane po zmianie stanu wyÅ›wietlania ekranu powitalnego. + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration` (float, domyÅ›lnie `2`): okreÅ›la liczbÄ™ sekund dla ekranu powitalnego zanikanie efekt do wykonać. + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner` (wartość logiczna, domyÅ›lnie `true`): zestaw na `false` , aby ukryć pokrÄ™tÅ‚a ekran powitalny. + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.Hide + +Odrzucić ten opryskaæ têcza. + + navigator.splashscreen.hide(); + + +### Jeżyna 10, WP8, iOS dziwactwo + +Plik `config.xml` `AutoHideSplashScreen` ustawienie musi być `false`. Opóźnienia, ukrywanie ekranu powitalnego przez dwie sekundy, dodać timer nastÄ™pujÄ…cych w `deviceready` obsÅ‚uga zdarzeÅ„: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +WyÅ›wietla ekran powitalny. + + navigator.splashscreen.show(); + + +Aplikacja nie można wywoÅ‚ać `navigator.splashscreen.show()`, aż aplikacja zostaÅ‚a uruchomiona i zdarzenie `deviceready` zostaÅ‚ zwolniony. Ale ponieważ zazwyczaj opryskać tÄ™cza ma być widoczne przed rozpoczÄ™ciem aplikacji, wydaje siÄ™ sprzeczne z celem ekranu powitalnego. Dostarczanie niektórych konfiguracji w `pliku config.xml` bÄ™dzie automatycznie `show` splash na ekranie natychmiast po uruchomienie aplikacji i przed peÅ‚ni rozpoczÄ…Å‚ i odebraÅ‚ zdarzenie `deviceready`. Aby uzyskać wiÄ™cej informacji na robienie tej konfiguracji, zobacz [ikony i ekrany powitalne w aplikacjach](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html). Z tego powodu jest maÅ‚o prawdopodobne, należy zadzwonić `navigator.splashscreen.show()`, aby wyÅ›wietlić ekran powitalny dla uruchamiania aplikacji.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/pl/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/pl/index.md new file mode 100644 index 00000000..33045cb7 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/pl/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +Ten plugin wyÅ›wietla i ukrywa ekran powitalny podczas uruchamiania aplikacji. + +## Instalacja + + cordova plugin add cordova-plugin-splashscreen + + +## ObsÅ‚ugiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Windows Phone 7 i 8 +* Windows 8 + +## Metody + +* splashscreen.show +* splashscreen.Hide + +### Dziwactwa Androida + +W pliku config.xml musisz dodać nastÄ™pujÄ…ce preferencje: + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +Gdzie foo jest nazwÄ… pliku ekranu powitalnego, najlepiej 9 Å‚atce. Upewnij siÄ™ dodać pliki splashcreen do katalogu res/xml w odpowiednich folderach. Drugi parametr reprezentuje, jak dÅ‚ugo ekranu powitalnego pojawi siÄ™ w milisekundach. DomyÅ›lnie 3000 ms. Aby uzyskać wiÄ™cej informacji, zobacz [ikony i ekrany powitalne w aplikacjach][1]. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.Hide + +Odrzucić ten opryskaæ têcza. + + navigator.splashscreen.hide(); + + +### Jeżyna 10, WP8, iOS dziwactwo + +Plik `config.xml` `AutoHideSplashScreen` ustawienie musi być `false`. Opóźnienia, ukrywanie ekranu powitalnego przez dwie sekundy, dodać timer nastÄ™pujÄ…cych w `deviceready` obsÅ‚uga zdarzeÅ„: + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +WyÅ›wietla ekran powitalny. + + navigator.splashscreen.show(); + + +Aplikacja nie można wywoÅ‚ać `navigator.splashscreen.show()`, aż aplikacja zostaÅ‚a uruchomiona i zdarzenie `deviceready` zostaÅ‚ zwolniony. Ale ponieważ zazwyczaj opryskać tÄ™cza ma być widoczne przed rozpoczÄ™ciem aplikacji, wydaje siÄ™ sprzeczne z celem ekranu powitalnego. Dostarczanie niektórych konfiguracji w `pliku config.xml` bÄ™dzie automatycznie `show` splash na ekranie natychmiast po uruchomienie aplikacji i przed peÅ‚ni rozpoczÄ…Å‚ i odebraÅ‚ zdarzenie `deviceready`. Aby uzyskać wiÄ™cej informacji na robienie tej konfiguracji, zobacz [ikony i ekrany powitalne w aplikacjach][1]. Z tego powodu jest maÅ‚o prawdopodobne, należy zadzwonić `navigator.splashscreen.show()`, aby wyÅ›wietlić ekran powitalny dla uruchamiania aplikacji. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ru/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ru/index.md new file mode 100644 index 00000000..635c22d8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/ru/index.md @@ -0,0 +1,75 @@ +<!--- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +# cordova-plugin-splashscreen + +Ðтот плагин отображает и Ñкрывает Ñкран-заÑтавку при запуÑке приложениÑ. + +## УÑтановка + + cordova plugin add cordova-plugin-splashscreen + + +## Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* iOS +* Windows Phone 7 и 8 +* Windows 8 + +## Методы + +* splashscreen.show +* splashscreen.hide + +### ОÑобенноÑти Android + +Ð’ вашем файле config.xml необходимо добавить Ñледующие наÑтройки: + +`<preference name="SplashScreen" value="foo" />` `<preference name="SplashScreenDelay" value="10000" />` + +Где foo Ñто Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð° splashscreen, желательно 9 заплатку. УбедитеÑÑŒ в том добавить ваши splashcreen файлы в папку res/xml в ÑоответÑтвующие папки. Второй параметр предÑтавлÑет, как долго splashscreen поÑвитÑÑ Ð² миллиÑекундах. По умолчанию он 3000 МС. Увидеть [иконки и заÑтавки][1] Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð¹ информации. + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.hide + +Закройте Ñкран-заÑтавка. + + Navigator.SplashScreen.Hide(); + + +### ОÑобенноÑти BlackBerry 10, WP8, iOS + +`config.xml`Файла `AutoHideSplashScreen` должен быть `false` . Ð”Ð»Ñ Ð·Ð°Ð´ÐµÑ€Ð¶ÐºÐ¸ ÑÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ð·Ð°Ñтавки на две Ñекунды, добавить таймер, например в `deviceready` обработчик Ñобытий: + + setTimeout(function() {navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +Отображает Ñкран-заÑтавку. + + Navigator.SplashScreen.Show(); + + +Ваше приложение не может вызвать `navigator.splashscreen.show()` до тех пор, пока приложение началаÑÑŒ и `deviceready` Ñобытие инициировано. Ðо поÑкольку обычно Ñкран-заÑтавка должен быть видимым до начала вашего приложениÑ, что казалоÑÑŒ бы поражение цели Ñкрана-заÑтавки. ПредоÑтавление некоторых конфигурации в `config.xml` будет автоматичеÑки `show` Ñкран-заÑтавку Ñразу же поÑле запуÑка вашего Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð¸ перед его полноÑтью запущен и получил `deviceready` Ñобытие. Увидеть [иконки и заÑтавки][1] Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð¹ информации на делать Ñтой конфигурации. По Ñтой причине маловероÑтно, вам нужно вызвать `navigator.splashscreen.show()` Ð´Ð»Ñ Ð¾Ñ‚Ð¾Ð±Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ Ñкрана-заÑтавки Ð´Ð»Ñ Ð·Ð°Ð¿ÑƒÑка приложениÑ. diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/zh/README.md new file mode 100644 index 00000000..da37405b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/zh/README.md @@ -0,0 +1,119 @@ +<!-- +# license: 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-plugin-splashscreen + +[](https://travis-ci.org/apache/cordova-plugin-splashscreen) + +這個外掛程å¼é¡¯ç¤ºå’Œéš±è—在應用程å¼å•Ÿå‹•期間的åˆå§‹èž¢å¹•。 + +## å®‰è£ + + // npm hosted (new) id + cordova plugin add cordova-plugin-splashscreen + // you may also install directly from this repo + cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git + + +## 支æ´çš„平臺 + + * 亞馬éœç« OS + * Android 系統 + * 黑莓 10 + * iOS + * Windows Phone 7 å’Œ 8 + * Windows 8 + * Windows + * ç€è¦½å™¨ + +## 方法 + + * splashscreen.show + * splashscreen.hide + +### Android 的怪癖 + +åœ¨ä½ çš„`config.xml`ï¼Œæ‚¨éœ€è¦æ·»åŠ ä»¥ä¸‹å„ªæƒ : + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + <preference name="SplashMaintainAspectRatio" value="true|false" /> + + +美åšåœ¨å“ªè£¡é–ƒå±æª”,最好是 9 ä¿®è£œç¨‹å¼æª”çš„å稱。 è«‹ç¢ºä¿æ‚¨çš„ splashcreen æª”æ·»åŠ åˆ° res/xml 目錄下相應的資料夾。 ç¬¬äºŒå€‹åƒæ•¸è¡¨ç¤ºå¤šä¹…é–ƒå±æœƒé¡¯ç¤ºä»¥æ¯«ç§’為單ä½ã€‚ 它將é è¨ç‚º 3000 毫秒。 有關更多資訊,請åƒè¦‹ [圖示和啟動畫é¢](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html)。 + +"SplashMaintainAspectRatio"首é¸é …是å¯é¸çš„。 如果è¨ç½®ç‚º true,å¯ç¹ªè£½çš„åˆå§‹èž¢å¹•䏿œƒæ‹‰ä¼¸ä»¥é©åˆèž¢å¹•,但相ååªæ˜¯"覆蓋"èž¢å¹•ï¼Œåƒ CSS"背景-大å°: è“‹"。 這是éžå¸¸æœ‰ç”¨çš„ä¸èƒ½ä»¥ä»»ä½•æ–¹å¼ï¼Œä¾‹å¦‚ç•¶ä»–å€‘åŒ…å«æ–‡æœ¬æˆ–風景畸變閃å±åœ–åƒæ™‚。 æ¤è¨ç½®é©ç”¨äºŽæœ‰å¤§åˆ©æ½¤ (安全å€),å¯ä»¥å®‰å…¨åœ°è£å‰ªä¸åŒé•·å¯¬æ¯”與螢幕上的圖åƒã€‚ + +該外掛程å¼é‡æ–°è¼‰å…¥åˆå§‹å¯ç¹ªè£½åªè¦æ–¹å‘發生變化,所以您å¯ä»¥æŒ‡å®šä¸åŒçš„ç•«æ¿ç‚ºç¸±å‘å’Œæ©«å‘æ–¹å‘。 + +### ç€è¦½å™¨çš„æ€ªç™– + +ä½ å¯ä»¥ç”¨ä½ çš„`config.xml`下列優先é¸é …: + + <platform name="browser"> + <preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" --> + <preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" --> + <preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" --> + <preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" --> + <preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" --> + <preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" --> + </platform> + + +### iOS 的怪癖 + + * `FadeSplashScreen`(é è¨ç‚º`true`的布林值): è¨ç½®ç‚º`false` ,以防æ¢å‡ºç¾é–ƒå±è¡°è½å’Œé€€å‡ºå…¶é¡¯ç¤ºç‹€æ…‹ç™¼ç”Ÿè®ŠåŒ–時。 + + <preference name="FadeSplashScreen" value="false"/> + + + * `FadeSplashScreenDuration`(float,é è¨ç‚º`2`): 指定的閃å±ç§’數淡出效果來執行。 + + <preference name="FadeSplashScreenDuration" value="4"/> + + + * `ShowSplashScreenSpinner`(boolean, `true`的布林值): è¨ç½®ç‚º`false`來隱è—åˆå§‹èž¢å¹•微調框。 + + <preference name="ShowSplashScreenSpinner" value="false"/> + + +## splashscreen.hide + +解雇的閃å±ã€‚ + + navigator.splashscreen.hide(); + + +### 黑莓 10,WP8,iOS 怪癖 + +`config.xml` 檔 `AutoHideSplashScreen` è¨ç½®å¿…é ˆæ˜¯ `å‡` 的。 è‹¥è¦å»¶é²å…©ç§’é˜éš±è—的閃å±ï¼Œ`deviceready` 事件處ç†å¸¸å¼ä¸æ·»åŠ ä¸€å€‹è¨ˆæ™‚å™¨ï¼Œå¦‚ä¸‹æ‰€ç¤ºï¼š + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +顯示åˆå§‹èž¢å¹•。 + + navigator.splashscreen.show(); + + +您的應用程å¼ç„¡æ³•調用 `navigator.splashscreen.show()`,直到該應用程å¼å·²å•Ÿå‹•,且觸發了 `deviceready` 事件。 但是,由於通常的閃å±ç‚ºäº†æ˜¯å¯è¦‹çš„在您的應用程å¼å•Ÿå‹•之å‰ï¼Œé€™ä¼¼ä¹Žæœƒæ‰“æ•—é–ƒå±çš„目的。 æä¾›ä¸€äº›é…置在 `config.xml` ä¸çš„æœƒè‡ªå‹• `show` åˆå§‹èž¢å¹•您的應用程å¼å•Ÿå‹•後立å³å’Œä¹‹å‰å®ƒå·²ç¶“完全起æ¥ä¸¦æ”¶åˆ° `deviceready` 事件。 åšé€™ç¨®é…置的詳細資訊,請åƒé–± [圖示和啟動畫é¢](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html)。 出於æ¤åŽŸå› ï¼Œä¸å¤ªå¯èƒ½æ‚¨éœ€è¦èª¿ç”¨ `navigator.splashscreen.show()`,使åˆå§‹èž¢å¹•å¯è¦‹ç‚ºæ‡‰ç”¨ç¨‹å¼å•Ÿå‹•。
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/doc/zh/index.md b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/zh/index.md new file mode 100644 index 00000000..efb309d0 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/doc/zh/index.md @@ -0,0 +1,78 @@ +<!--- + 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-plugin-splashscreen + +這個外掛程å¼é¡¯ç¤ºå’Œéš±è—在應用程å¼å•Ÿå‹•期間的åˆå§‹èž¢å¹•。 + +## å®‰è£ + + cordova plugin add cordova-plugin-splashscreen + + +## 支æ´çš„平臺 + +* 亞馬éœç« OS +* Android 系統 +* 黑莓 10 +* iOS +* Windows Phone 7 å’Œ 8 +* Windows 8 + +## 方法 + +* splashscreen.show +* splashscreen.hide + +### Android 的怪癖 + +åœ¨ä½ çš„ config.xmlï¼Œæ‚¨éœ€è¦æ·»åŠ ä»¥ä¸‹å„ªæƒ ï¼š + + <preference name="SplashScreen" value="foo" /> + <preference name="SplashScreenDelay" value="10000" /> + + +美åšåœ¨å“ªè£¡é–ƒå±æª”,最好是 9 ä¿®è£œç¨‹å¼æª”çš„å稱。 è«‹ç¢ºä¿æ‚¨çš„ splashcreen æª”æ·»åŠ åˆ° res/xml 目錄下相應的資料夾。 ç¬¬äºŒå€‹åƒæ•¸è¡¨ç¤ºå¤šä¹…é–ƒå±æœƒé¡¯ç¤ºä»¥æ¯«ç§’為單ä½ã€‚ 它將é è¨ç‚º 3000 毫秒。 有關更多資訊,請åƒè¦‹ [圖示和啟動畫é¢][1]。 + + [1]: http://cordova.apache.org/docs/en/edge/config_ref_images.md.html + +## splashscreen.hide + +解雇的閃å±ã€‚ + + navigator.splashscreen.hide(); + + +### 黑莓 10,WP8,iOS 怪癖 + +`config.xml` 檔 `AutoHideSplashScreen` è¨ç½®å¿…é ˆæ˜¯ `å‡` 的。 è‹¥è¦å»¶é²å…©ç§’é˜éš±è—的閃å±ï¼Œ`deviceready` 事件處ç†å¸¸å¼ä¸æ·»åŠ ä¸€å€‹è¨ˆæ™‚å™¨ï¼Œå¦‚ä¸‹æ‰€ç¤ºï¼š + + setTimeout(function() { + navigator.splashscreen.hide(); + }, 2000); + + +## splashscreen.show + +顯示åˆå§‹èž¢å¹•。 + + navigator.splashscreen.show(); + + +您的應用程å¼ç„¡æ³•調用 `navigator.splashscreen.show()`,直到該應用程å¼å·²å•Ÿå‹•,且觸發了 `deviceready` 事件。 但是,由於通常的閃å±ç‚ºäº†æ˜¯å¯è¦‹çš„在您的應用程å¼å•Ÿå‹•之å‰ï¼Œé€™ä¼¼ä¹Žæœƒæ‰“æ•—é–ƒå±çš„目的。 æä¾›ä¸€äº›é…置在 `config.xml` ä¸çš„æœƒè‡ªå‹• `show` åˆå§‹èž¢å¹•您的應用程å¼å•Ÿå‹•後立å³å’Œä¹‹å‰å®ƒå·²ç¶“完全起æ¥ä¸¦æ”¶åˆ° `deviceready` 事件。 åšé€™ç¨®é…置的詳細資訊,請åƒé–± [圖示和啟動畫é¢][1]。 出於æ¤åŽŸå› ï¼Œä¸å¤ªå¯èƒ½æ‚¨éœ€è¦èª¿ç”¨ `navigator.splashscreen.show()`,使åˆå§‹èž¢å¹•å¯è¦‹ç‚ºæ‡‰ç”¨ç¨‹å¼å•Ÿå‹•。 diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/package.json b/StoneIsland/plugins/cordova-plugin-splashscreen/package.json new file mode 100644 index 00000000..447ac7e9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/package.json @@ -0,0 +1,45 @@ +{ + "name": "cordova-plugin-splashscreen", + "version": "2.1.0", + "description": "Cordova Splashscreen Plugin", + "cordova": { + "id": "cordova-plugin-splashscreen", + "platforms": [ + "android", + "amazon-fireos", + "ubuntu", + "ios", + "blackberry10", + "wp8", + "windows8", + "windows", + "tizen" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/apache/cordova-plugin-splashscreen" + }, + "keywords": [ + "cordova", + "splashscreen", + "ecosystem:cordova", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-blackberry10", + "cordova-wp8", + "cordova-windows8", + "cordova-windows", + "cordova-tizen" + ], + "engines": [ + { + "name": "cordova-android", + "version": ">=3.6.0" + } + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/plugin.xml b/StoneIsland/plugins/cordova-plugin-splashscreen/plugin.xml new file mode 100644 index 00000000..e6370fa9 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/plugin.xml @@ -0,0 +1,134 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="cordova-plugin-splashscreen" + version="2.1.0"> + <name>Splashscreen</name> + <description>Cordova Splashscreen Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,splashscreen</keywords> + <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git</repo> + <issue>https://issues.apache.org/jira/browse/CB/component/12320653</issue> + + <engines> + <engine name="cordova-android" version=">=3.6.0" /><!-- Requires CordovaPlugin.preferences --> + </engines> + + <js-module src="www/splashscreen.js" name="SplashScreen"> + <clobbers target="navigator.splashscreen" /> + </js-module> + + <!-- android --> + <platform name="android"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="SplashScreen"> + <param name="android-package" value="org.apache.cordova.splashscreen.SplashScreen"/> + <param name="onload" value="true"/> + </feature> + </config-file> + + <source-file src="src/android/SplashScreen.java" target-dir="src/org/apache/cordova/splashscreen" /> + </platform> + + <!-- amazon-fireos --> + <platform name="amazon-fireos"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="SplashScreen"> + <param name="android-package" value="org.apache.cordova.splashscreen.SplashScreen"/> + </feature> + </config-file> + + <source-file src="src/android/SplashScreen.java" target-dir="src/org/apache/cordova/splashscreen" /> + </platform> + + <!-- ubuntu --> + <platform name="ubuntu"> + <header-file src="src/ubuntu/splashscreen.h" /> + <source-file src="src/ubuntu/splashscreen.cpp" /> + </platform> + + <!-- ios --> + <platform name="ios"> + <config-file target="config.xml" parent="/*"> + <feature name="SplashScreen"> + <param name="ios-package" value="CDVSplashScreen"/> + <param name="onload" value="true"/> + </feature> + </config-file> + + <header-file src="src/ios/CDVSplashScreen.h" /> + <source-file src="src/ios/CDVSplashScreen.m" /> + <header-file src="src/ios/CDVViewController+SplashScreen.h" /> + <source-file src="src/ios/CDVViewController+SplashScreen.m" /> + + <framework src="CoreGraphics.framework" /> + </platform> + + <!-- blackberry10 --> + <platform name="blackberry10"> + <source-file src="src/blackberry10/index.js" target-dir="SplashScreen" /> + <config-file target="www/config.xml" parent="/widget"> + <feature name="SplashScreen" value="SplashScreen"/> + </config-file> + </platform> + + <!-- wp8 --> + <platform name="wp8"> + <config-file target="config.xml" parent="/*"> + <feature name="SplashScreen"> + <param name="wp-package" value="SplashScreen"/> + <param name="onload" value="true"/> + </feature> + </config-file> + + <source-file src="src/wp/SplashScreen.cs" /> + <source-file src="src/wp/ResolutionHelper.cs" /> + + </platform> + + <!-- windows8 --> + <platform name="windows8"> + <js-module src="www/windows/SplashScreenProxy.js" name="SplashScreenProxy"> + <merges target="" /> + </js-module> + </platform> + + <!-- windows --> + <platform name="windows"> + <js-module src="www/windows/SplashScreenProxy.js" name="SplashScreenProxy"> + <merges target="" /> + </js-module> + </platform> + + <!-- tizen --> + <platform name="tizen"> + <js-module src="src/tizen/SplashScreenProxy.js" name="SplashScreenProxy"> + <runs /> + </js-module> + </platform> + + <!-- browser --> + <platform name="browser"> + <js-module src="src/browser/SplashScreenProxy.js" name="SplashScreenProxy"> + <runs /> + </js-module> + </platform> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/android/SplashScreen.java b/StoneIsland/plugins/cordova-plugin-splashscreen/src/android/SplashScreen.java new file mode 100644 index 00000000..75ad724c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/android/SplashScreen.java @@ -0,0 +1,328 @@ +/* + 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. +*/ + +package org.apache.cordova.splashscreen; + +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.res.Configuration; +import android.graphics.Color; +import android.os.Handler; +import android.view.Display; +import android.view.View; +import android.view.ViewGroup.LayoutParams; +import android.view.WindowManager; +import android.widget.ImageView; +import android.widget.LinearLayout; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.CordovaWebView; +import org.json.JSONArray; +import org.json.JSONException; + +public class SplashScreen extends CordovaPlugin { + private static final String LOG_TAG = "SplashScreen"; + // Cordova 3.x.x has a copy of this plugin bundled with it (SplashScreenInternal.java). + // Enable functionality only if running on 4.x.x. + private static final boolean HAS_BUILT_IN_SPLASH_SCREEN = Integer.valueOf(CordovaWebView.CORDOVA_VERSION.split("\\.")[0]) < 4; + private static Dialog splashDialog; + private static ProgressDialog spinnerDialog; + private static boolean firstShow = true; + + /** + * Displays the splash drawable. + */ + private ImageView splashImageView; + + /** + * Remember last device orientation to detect orientation changes. + */ + private int orientation; + + // Helper to be compile-time compatible with both Cordova 3.x and 4.x. + private View getView() { + try { + return (View)webView.getClass().getMethod("getView").invoke(webView); + } catch (Exception e) { + return (View)webView; + } + } + + @Override + protected void pluginInitialize() { + if (HAS_BUILT_IN_SPLASH_SCREEN || !firstShow) { + return; + } + // Make WebView invisible while loading URL + getView().setVisibility(View.INVISIBLE); + int drawableId = preferences.getInteger("SplashDrawableId", 0); + if (drawableId == 0) { + String splashResource = preferences.getString("SplashScreen", "screen"); + if (splashResource != null) { + drawableId = cordova.getActivity().getResources().getIdentifier(splashResource, "drawable", cordova.getActivity().getClass().getPackage().getName()); + if (drawableId == 0) { + drawableId = cordova.getActivity().getResources().getIdentifier(splashResource, "drawable", cordova.getActivity().getPackageName()); + } + preferences.set("SplashDrawableId", drawableId); + } + } + + // Save initial orientation. + orientation = cordova.getActivity().getResources().getConfiguration().orientation; + + firstShow = false; + loadSpinner(); + showSplashScreen(true); + } + + /** + * Shorter way to check value of "SplashMaintainAspectRatio" preference. + */ + private boolean isMaintainAspectRatio () { + return preferences.getBoolean("SplashMaintainAspectRatio", false); + } + + @Override + public void onPause(boolean multitasking) { + if (HAS_BUILT_IN_SPLASH_SCREEN) { + return; + } + // hide the splash screen to avoid leaking a window + this.removeSplashScreen(); + } + + @Override + public void onDestroy() { + if (HAS_BUILT_IN_SPLASH_SCREEN) { + return; + } + // hide the splash screen to avoid leaking a window + this.removeSplashScreen(); + // If we set this to true onDestroy, we lose track when we go from page to page! + //firstShow = true; + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + if (action.equals("hide")) { + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + webView.postMessage("splashscreen", "hide"); + } + }); + } else if (action.equals("show")) { + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + webView.postMessage("splashscreen", "show"); + } + }); + } else if (action.equals("spinnerStart")) { + if (!HAS_BUILT_IN_SPLASH_SCREEN) { + final String title = args.getString(0); + final String message = args.getString(1); + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + spinnerStart(title, message); + } + }); + } + } else { + return false; + } + + callbackContext.success(); + return true; + } + + @Override + public Object onMessage(String id, Object data) { + if (HAS_BUILT_IN_SPLASH_SCREEN) { + return null; + } + if ("splashscreen".equals(id)) { + if ("hide".equals(data.toString())) { + this.removeSplashScreen(); + } else { + this.showSplashScreen(false); + } + } else if ("spinner".equals(id)) { + if ("stop".equals(data.toString())) { + this.spinnerStop(); + getView().setVisibility(View.VISIBLE); + } + } else if ("onReceivedError".equals(id)) { + spinnerStop(); + } + return null; + } + + // Don't add @Override so that plugin still compiles on 3.x.x for a while + public void onConfigurationChanged(Configuration newConfig) { + if (newConfig.orientation != orientation) { + orientation = newConfig.orientation; + + // Splash drawable may change with orientation, so reload it. + if (splashImageView != null) { + int drawableId = preferences.getInteger("SplashDrawableId", 0); + if (drawableId != 0) { + splashImageView.setImageDrawable(cordova.getActivity().getResources().getDrawable(drawableId)); + } + } + } + } + + private void removeSplashScreen() { + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + if (splashDialog != null && splashDialog.isShowing()) { + splashDialog.dismiss(); + splashDialog = null; + splashImageView = null; + } + } + }); + } + + /** + * Shows the splash screen over the full Activity + */ + @SuppressWarnings("deprecation") + private void showSplashScreen(final boolean hideAfterDelay) { + final int splashscreenTime = preferences.getInteger("SplashScreenDelay", 3000); + final int drawableId = preferences.getInteger("SplashDrawableId", 0); + + // If the splash dialog is showing don't try to show it again + if (splashDialog != null && splashDialog.isShowing()) { + return; + } + if (drawableId == 0 || (splashscreenTime <= 0 && hideAfterDelay)) { + return; + } + + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + // Get reference to display + Display display = cordova.getActivity().getWindowManager().getDefaultDisplay(); + Context context = webView.getContext(); + + // Use an ImageView to render the image because of its flexible scaling options. + splashImageView = new ImageView(context); + splashImageView.setImageResource(drawableId); + LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); + splashImageView.setLayoutParams(layoutParams); + + splashImageView.setMinimumHeight(display.getHeight()); + splashImageView.setMinimumWidth(display.getWidth()); + + // TODO: Use the background color of the webView's parent instead of using the preference. + splashImageView.setBackgroundColor(preferences.getInteger("backgroundColor", Color.BLACK)); + + if (isMaintainAspectRatio()) { + // CENTER_CROP scale mode is equivalent to CSS "background-size:cover" + splashImageView.setScaleType(ImageView.ScaleType.CENTER_CROP); + } + else { + // FIT_XY scales image non-uniformly to fit into image view. + splashImageView.setScaleType(ImageView.ScaleType.FIT_XY); + } + + // Create and show the dialog + splashDialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar); + // check to see if the splash screen should be full screen + if ((cordova.getActivity().getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) + == WindowManager.LayoutParams.FLAG_FULLSCREEN) { + splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); + } + splashDialog.setContentView(splashImageView); + splashDialog.setCancelable(false); + splashDialog.show(); + + // Set Runnable to remove splash screen just in case + if (hideAfterDelay) { + final Handler handler = new Handler(); + handler.postDelayed(new Runnable() { + public void run() { + removeSplashScreen(); + } + }, splashscreenTime); + } + } + }); + } + + /* + * Load the spinner + */ + private void loadSpinner() { + // If loadingDialog property, then show the App loading dialog for first page of app + String loading = null; + if (webView.canGoBack()) { + loading = preferences.getString("LoadingDialog", null); + } + else { + loading = preferences.getString("LoadingPageDialog", null); + } + if (loading != null) { + String title = ""; + String message = "Loading Application..."; + + if (loading.length() > 0) { + int comma = loading.indexOf(','); + if (comma > 0) { + title = loading.substring(0, comma); + message = loading.substring(comma + 1); + } + else { + title = ""; + message = loading; + } + } + spinnerStart(title, message); + } + } + + private void spinnerStart(final String title, final String message) { + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + spinnerStop(); + spinnerDialog = ProgressDialog.show(webView.getContext(), title, message, true, true, + new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + spinnerDialog = null; + } + }); + } + }); + } + + private void spinnerStop() { + cordova.getActivity().runOnUiThread(new Runnable() { + public void run() { + if (spinnerDialog != null && spinnerDialog.isShowing()) { + spinnerDialog.dismiss(); + spinnerDialog = null; + } + } + }); + } +} diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/blackberry10/index.js b/StoneIsland/plugins/cordova-plugin-splashscreen/src/blackberry10/index.js new file mode 100644 index 00000000..bd7e48c8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/blackberry10/index.js @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Research In Motion Limited. + * + * Licensed 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 = { + show: function (success, fail, args, env) { + var result = new PluginResult(args, env); + result.error("Not supported on platform", false); + }, + + hide: function (success, fail, args, env) { + var result = new PluginResult(args, env); + window.qnx.webplatform.getApplication().windowVisible = true; + result.ok(undefined, false); + } +}; diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js b/StoneIsland/plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js new file mode 100644 index 00000000..d19f8c87 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js @@ -0,0 +1,138 @@ +/* + * + * 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. + * +*/ +// Default parameter values including image size can be changed in `config.xml` +var splashImageWidth = 170; +var splashImageHeight = 200; +var position = { x: 0, y: 0, width: splashImageWidth, height: splashImageHeight }; +var splash = null; // +var localSplash; // the image to display +var localSplashImage; +var bgColor = "#464646"; +var imageSrc = 'img/logo.png'; +var splashScreenDelay = 3000; // in milliseconds +var showSplashScreen = true; // show splashcreen by default +var configHelper = cordova.require('cordova/confighelper'); + +function updateImageLocation() { + position.width = Math.min(splashImageWidth, window.innerWidth); + position.height = position.width * (splashImageHeight / splashImageWidth); + + localSplash.style.width = window.innerWidth + "px"; + localSplash.style.height = window.innerHeight + "px"; + localSplash.style.top = "0px"; + localSplash.style.left = "0px"; + + localSplashImage.style.top = "50%"; + localSplashImage.style.left = "50%"; + localSplashImage.style.height = position.height + "px"; + localSplashImage.style.width = position.width + "px"; + localSplashImage.style.marginTop = (-position.height / 2) + "px"; + localSplashImage.style.marginLeft = (-position.width / 2) + "px"; +} + +function onResize() { + updateImageLocation(); +} + +var SplashScreen = { + setBGColor: function (cssBGColor) { + bgColor = cssBGColor; + if (localSplash) { + localSplash.style.backgroundColor = bgColor; + } + }, + show: function () { + if(!localSplash) { + window.addEventListener("resize", onResize, false); + localSplash = document.createElement("div"); + localSplash.style.backgroundColor = bgColor; + localSplash.style.position = "absolute"; + + localSplashImage = document.createElement("img"); + localSplashImage.src = imageSrc; + localSplashImage.style.position = "absolute"; + + updateImageLocation(); + + localSplash.appendChild(localSplashImage); + document.body.appendChild(localSplash); + } + }, + hide: function () { + if(localSplash) { + window.removeEventListener("resize", onResize, false); + document.body.removeChild(localSplash); + localSplash = null; + } + } +}; + +/** + * Reads preferences via ConfigHelper and substitutes default parameters. + */ +function readPreferencesFromCfg(cfg) { + try { + var value = cfg.getPreferenceValue('ShowSplashScreen'); + if(typeof value != 'undefined') { + showSplashScreen = value === 'true'; + } + + splashScreenDelay = cfg.getPreferenceValue('SplashScreenDelay') || splashScreenDelay; + imageSrc = cfg.getPreferenceValue('SplashScreen') || imageSrc; + bgColor = cfg.getPreferenceValue('SplashScreenBackgroundColor') || bgColor; + splashImageWidth = cfg.getPreferenceValue('SplashScreenWidth') || splashImageWidth; + splashImageHeight = cfg.getPreferenceValue('SplashScreenHeight') || splashImageHeight; + } catch(e) { + var msg = '[Browser][SplashScreen] Error occured on loading preferences from config.xml: ' + JSON.stringify(e); + console.error(msg); + error(msg); + } +} + +/** + * Shows and hides splashscreen if it is enabled, with a delay according the current preferences. + */ +function showAndHide() { + if(showSplashScreen) { + SplashScreen.show(); + + window.setTimeout(function() { + SplashScreen.hide(); + }, splashScreenDelay); + } +} + +/** + * Tries to read config.xml and override default properties and then shows and hides splashcreen if it is enabled. + */ +(function initAndShow() { + configHelper.readConfig(function(config) { + readPreferencesFromCfg(config); + showAndHide(); + }, function(err) { + console.error(err); + }); +})(); + +module.exports = SplashScreen; + +require("cordova/exec/proxy").add("SplashScreen", SplashScreen); + diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.h b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.h new file mode 100644 index 00000000..0d6ae397 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.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. + */ + +#import <Foundation/Foundation.h> +#import <Cordova/CDVPlugin.h> + +typedef struct { + BOOL iPhone; + BOOL iPad; + BOOL iPhone5; + BOOL iPhone6; + BOOL iPhone6Plus; + BOOL retina; + +} CDV_iOSDevice; + +@interface CDVSplashScreen : CDVPlugin { + UIActivityIndicatorView* _activityView; + UIImageView* _imageView; + NSString* _curImageName; + BOOL _visible; +} + +- (void)show:(CDVInvokedUrlCommand*)command; +- (void)hide:(CDVInvokedUrlCommand*)command; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.m b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.m new file mode 100644 index 00000000..43b356ad --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVSplashScreen.m @@ -0,0 +1,330 @@ +/* + 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 "CDVSplashScreen.h" +#import <Cordova/CDVViewController.h> +#import <Cordova/CDVScreenOrientationDelegate.h> +#import "CDVViewController+SplashScreen.h" + +#define kSplashScreenDurationDefault 0.25f + + +@implementation CDVSplashScreen + +- (void)pluginInitialize +{ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageDidLoad) name:CDVPageDidLoadNotification object:self.webView]; + + [self setVisible:YES]; +} + +- (void)show:(CDVInvokedUrlCommand*)command +{ + [self setVisible:YES]; +} + +- (void)hide:(CDVInvokedUrlCommand*)command +{ + [self setVisible:NO]; +} + +- (void)pageDidLoad +{ + id autoHideSplashScreenValue = [self.commandDelegate.settings objectForKey:[@"AutoHideSplashScreen" lowercaseString]]; + + // if value is missing, default to yes + if ((autoHideSplashScreenValue == nil) || [autoHideSplashScreenValue boolValue]) { + [self setVisible:NO]; + } +} + +- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context +{ + [self updateImage]; +} + +- (void)createViews +{ + /* + * The Activity View is the top spinning throbber in the status/battery bar. We init it with the default Grey Style. + * + * whiteLarge = UIActivityIndicatorViewStyleWhiteLarge + * white = UIActivityIndicatorViewStyleWhite + * gray = UIActivityIndicatorViewStyleGray + * + */ + + // Determine whether rotation should be enabled for this device + // Per iOS HIG, landscape is only supported on iPad and iPhone 6+ + CDV_iOSDevice device = [self getCurrentDevice]; + BOOL autorotateValue = (device.iPad || device.iPhone6Plus) ? + [(CDVViewController *)self.viewController shouldAutorotateDefaultValue] : + NO; + + [(CDVViewController *)self.viewController setEnabledAutorotation:autorotateValue]; + + NSString* topActivityIndicator = [self.commandDelegate.settings objectForKey:[@"TopActivityIndicator" lowercaseString]]; + UIActivityIndicatorViewStyle topActivityIndicatorStyle = UIActivityIndicatorViewStyleGray; + + if ([topActivityIndicator isEqualToString:@"whiteLarge"]) { + topActivityIndicatorStyle = UIActivityIndicatorViewStyleWhiteLarge; + } else if ([topActivityIndicator isEqualToString:@"white"]) { + topActivityIndicatorStyle = UIActivityIndicatorViewStyleWhite; + } else if ([topActivityIndicator isEqualToString:@"gray"]) { + topActivityIndicatorStyle = UIActivityIndicatorViewStyleGray; + } + + UIView* parentView = self.viewController.view; + parentView.userInteractionEnabled = NO; // disable user interaction while splashscreen is shown + _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:topActivityIndicatorStyle]; + _activityView.center = CGPointMake(parentView.bounds.size.width / 2, parentView.bounds.size.height / 2); + _activityView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin + | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin; + [_activityView startAnimating]; + + // Set the frame & image later. + _imageView = [[UIImageView alloc] init]; + [parentView addSubview:_imageView]; + + id showSplashScreenSpinnerValue = [self.commandDelegate.settings objectForKey:[@"ShowSplashScreenSpinner" lowercaseString]]; + // backwards compatibility - if key is missing, default to true + if ((showSplashScreenSpinnerValue == nil) || [showSplashScreenSpinnerValue boolValue]) { + [parentView addSubview:_activityView]; + } + + // Frame is required when launching in portrait mode. + // Bounds for landscape since it captures the rotation. + [parentView addObserver:self forKeyPath:@"frame" options:0 context:nil]; + [parentView addObserver:self forKeyPath:@"bounds" options:0 context:nil]; + + [self updateImage]; +} + +- (void)destroyViews +{ + [(CDVViewController *)self.viewController setEnabledAutorotation:[(CDVViewController *)self.viewController shouldAutorotateDefaultValue]]; + + [_imageView removeFromSuperview]; + [_activityView removeFromSuperview]; + _imageView = nil; + _activityView = nil; + _curImageName = nil; + + self.viewController.view.userInteractionEnabled = YES; // re-enable user interaction upon completion + [self.viewController.view removeObserver:self forKeyPath:@"frame"]; + [self.viewController.view removeObserver:self forKeyPath:@"bounds"]; +} + +- (CDV_iOSDevice) getCurrentDevice +{ + CDV_iOSDevice device; + + UIScreen* mainScreen = [UIScreen mainScreen]; + CGFloat mainScreenHeight = mainScreen.bounds.size.height; + CGFloat mainScreenWidth = mainScreen.bounds.size.width; + + int limit = MAX(mainScreenHeight,mainScreenWidth); + + device.iPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad); + device.iPhone = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone); + device.retina = ([mainScreen scale] == 2.0); + device.iPhone5 = (device.iPhone && limit == 568.0); + // note these below is not a true device detect, for example if you are on an + // iPhone 6/6+ but the app is scaled it will prob set iPhone5 as true, but + // this is appropriate for detecting the runtime screen environment + device.iPhone6 = (device.iPhone && limit == 667.0); + device.iPhone6Plus = (device.iPhone && limit == 736.0); + + return device; +} + +- (NSString*)getImageName:(UIInterfaceOrientation)currentOrientation delegate:(id<CDVScreenOrientationDelegate>)orientationDelegate device:(CDV_iOSDevice)device +{ + // Use UILaunchImageFile if specified in plist. Otherwise, use Default. + NSString* imageName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UILaunchImageFile"]; + + NSUInteger supportedOrientations = [orientationDelegate supportedInterfaceOrientations]; + + // Checks to see if the developer has locked the orientation to use only one of Portrait or Landscape + BOOL supportsLandscape = (supportedOrientations & UIInterfaceOrientationMaskLandscape); + BOOL supportsPortrait = (supportedOrientations & UIInterfaceOrientationMaskPortrait || supportedOrientations & UIInterfaceOrientationMaskPortraitUpsideDown); + // this means there are no mixed orientations in there + BOOL isOrientationLocked = !(supportsPortrait && supportsLandscape); + + if (imageName) { + imageName = [imageName stringByDeletingPathExtension]; + } else { + imageName = @"Default"; + } + + if (device.iPhone5) { // does not support landscape + imageName = [imageName stringByAppendingString:@"-568h"]; + } else if (device.iPhone6) { // does not support landscape + imageName = [imageName stringByAppendingString:@"-667h"]; + } else if (device.iPhone6Plus) { // supports landscape + if (isOrientationLocked) { + imageName = [imageName stringByAppendingString:(supportsLandscape ? @"-Landscape" : @"")]; + } else { + switch (currentOrientation) { + case UIInterfaceOrientationLandscapeLeft: + case UIInterfaceOrientationLandscapeRight: + imageName = [imageName stringByAppendingString:@"-Landscape"]; + break; + default: + break; + } + } + imageName = [imageName stringByAppendingString:@"-736h"]; + + } else if (device.iPad) { // supports landscape + if (isOrientationLocked) { + imageName = [imageName stringByAppendingString:(supportsLandscape ? @"-Landscape" : @"-Portrait")]; + } else { + switch (currentOrientation) { + case UIInterfaceOrientationLandscapeLeft: + case UIInterfaceOrientationLandscapeRight: + imageName = [imageName stringByAppendingString:@"-Landscape"]; + break; + + case UIInterfaceOrientationPortrait: + case UIInterfaceOrientationPortraitUpsideDown: + default: + imageName = [imageName stringByAppendingString:@"-Portrait"]; + break; + } + } + } + + return imageName; +} + +// Sets the view's frame and image. +- (void)updateImage +{ + NSString* imageName = [self getImageName:[[UIApplication sharedApplication] statusBarOrientation] delegate:(id<CDVScreenOrientationDelegate>)self.viewController device:[self getCurrentDevice]]; + + if (![imageName isEqualToString:_curImageName]) { + UIImage* img = [UIImage imageNamed:imageName]; + _imageView.image = img; + _curImageName = imageName; + } + + // Check that splash screen's image exists before updating bounds + if (_imageView.image) { + [self updateBounds]; + } else { + NSLog(@"WARNING: The splashscreen image named %@ was not found", imageName); + } +} + +- (void)updateBounds +{ + UIImage* img = _imageView.image; + CGRect imgBounds = (img) ? CGRectMake(0, 0, img.size.width, img.size.height) : CGRectZero; + + CGSize screenSize = [self.viewController.view convertRect:[UIScreen mainScreen].bounds fromView:nil].size; + UIInterfaceOrientation orientation = self.viewController.interfaceOrientation; + CGAffineTransform imgTransform = CGAffineTransformIdentity; + + /* If and only if an iPhone application is landscape-only as per + * UISupportedInterfaceOrientations, the view controller's orientation is + * landscape. In this case the image must be rotated in order to appear + * correctly. + */ + BOOL isIPad = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad; + if (UIInterfaceOrientationIsLandscape(orientation) && !isIPad) { + imgTransform = CGAffineTransformMakeRotation(M_PI / 2); + imgBounds.size = CGSizeMake(imgBounds.size.height, imgBounds.size.width); + } + + // There's a special case when the image is the size of the screen. + if (CGSizeEqualToSize(screenSize, imgBounds.size)) { + CGRect statusFrame = [self.viewController.view convertRect:[UIApplication sharedApplication].statusBarFrame fromView:nil]; + if (!(IsAtLeastiOSVersion(@"7.0"))) { + imgBounds.origin.y -= statusFrame.size.height; + } + } else if (imgBounds.size.width > 0) { + CGRect viewBounds = self.viewController.view.bounds; + CGFloat imgAspect = imgBounds.size.width / imgBounds.size.height; + CGFloat viewAspect = viewBounds.size.width / viewBounds.size.height; + // This matches the behaviour of the native splash screen. + CGFloat ratio; + if (viewAspect > imgAspect) { + ratio = viewBounds.size.width / imgBounds.size.width; + } else { + ratio = viewBounds.size.height / imgBounds.size.height; + } + imgBounds.size.height *= ratio; + imgBounds.size.width *= ratio; + } + + _imageView.transform = imgTransform; + _imageView.frame = imgBounds; +} + +- (void)setVisible:(BOOL)visible +{ + if (visible == _visible) { + return; + } + _visible = visible; + + id fadeSplashScreenValue = [self.commandDelegate.settings objectForKey:[@"FadeSplashScreen" lowercaseString]]; + id fadeSplashScreenDuration = [self.commandDelegate.settings objectForKey:[@"FadeSplashScreenDuration" lowercaseString]]; + + float fadeDuration = fadeSplashScreenDuration == nil ? kSplashScreenDurationDefault : [fadeSplashScreenDuration floatValue]; + + if ((fadeSplashScreenValue == nil) || ![fadeSplashScreenValue boolValue]) { + fadeDuration = 0; + } + + // Never animate the showing of the splash screen. + if (visible) { + if (_imageView == nil) { + [self createViews]; + } + } else if (fadeDuration == 0) { + [self destroyViews]; + } else { + __weak __typeof(self) weakSelf = self; + + [UIView transitionWithView:self.viewController.view + duration:fadeDuration + options:UIViewAnimationOptionTransitionNone + animations:^(void) { + __typeof(self) strongSelf = weakSelf; + if (strongSelf != nil) { + dispatch_async(dispatch_get_main_queue(), ^{ + [strongSelf->_activityView setAlpha:0]; + [strongSelf->_imageView setAlpha:0]; + }); + } + } + completion:^(BOOL finished) { + if (finished) { + dispatch_async(dispatch_get_main_queue(), ^{ + [weakSelf destroyViews]; + }); + } + } + ]; + } +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.h b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.h new file mode 100644 index 00000000..a948ea31 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.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 <Cordova/CDVViewController.h> + +@interface CDVViewController (SplashScreen) + +@property (nonatomic, assign) BOOL enabledAutorotation; +@property (nonatomic, readonly) BOOL shouldAutorotateDefaultValue; + + +@end diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.m b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.m new file mode 100644 index 00000000..5736b6f2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ios/CDVViewController+SplashScreen.m @@ -0,0 +1,82 @@ +/* + 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 "CDVViewController+SplashScreen.h" +#import <objc/runtime.h> + +@implementation CDVViewController (SplashScreen) + +@dynamic enabledAutorotation; + +- (void)setEnabledAutorotation:(BOOL)value +{ + objc_setAssociatedObject(self, + @selector(enabledAutorotation), + [NSNumber numberWithBool:value], + OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)enabledAutorotation +{ + NSNumber *number = (NSNumber *)objc_getAssociatedObject(self, @selector(enabledAutorotation)); + return [number boolValue]; +} + ++ (void)load +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [self class]; + + SEL originalSelector = @selector(shouldAutorotate); + SEL swizzledSelector = @selector(splash_shouldAutorotate); + + Method originalMethod = class_getInstanceMethod(class, originalSelector); + Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); + + BOOL didAddMethod = class_addMethod(class, + originalSelector, + method_getImplementation(swizzledMethod), + method_getTypeEncoding(swizzledMethod)); + + if (didAddMethod) { + class_replaceMethod(class, + swizzledSelector, + method_getImplementation(originalMethod), + method_getTypeEncoding(originalMethod)); + } else { + method_exchangeImplementations(originalMethod, swizzledMethod); + } + }); +} + +#pragma mark - Method Swizzling + +- (BOOL)splash_shouldAutorotate +{ + return self.enabledAutorotation; +} + + +- (BOOL)shouldAutorotateDefaultValue +{ + return [self splash_shouldAutorotate]; +} + +@end diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/tizen/SplashScreenProxy.js b/StoneIsland/plugins/cordova-plugin-splashscreen/src/tizen/SplashScreenProxy.js new file mode 100644 index 00000000..fbd9f35f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/tizen/SplashScreenProxy.js @@ -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. + * +*/ + +( function() { + +win = null; + +module.exports = { + show: function() { + if ( win === null ) { + win = window.open('splashscreen.html'); + } + }, + + hide: function() { + if ( win !== null ) { + win.close(); + win = null; + } + } +}; + +require("cordova/tizen/commandProxy").add("SplashScreen", module.exports); + +})(); diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/ubuntu/splashscreen.cpp b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ubuntu/splashscreen.cpp new file mode 100644 index 00000000..1c9ecac8 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ubuntu/splashscreen.cpp @@ -0,0 +1,42 @@ +/* + * + * Copyright 2013 Canonical Ltd. + * + * 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 <QQuickItem> + +#include "splashscreen.h" +#include <cordova.h> + +#define SPLASHSCREEN_STATE_NAME "splashscreen" + +Splashscreen::Splashscreen(Cordova *cordova): CPlugin(cordova) { +} + +void Splashscreen::show(int, int) { + m_cordova->rootObject()->setProperty("splashscreenPath", m_cordova->getSplashscreenPath()); + + m_cordova->pushViewState(SPLASHSCREEN_STATE_NAME); +} + +void Splashscreen::hide(int, int) { + m_cordova->popViewState(SPLASHSCREEN_STATE_NAME); +} diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/ubuntu/splashscreen.h b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ubuntu/splashscreen.h new file mode 100644 index 00000000..1d437f84 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/ubuntu/splashscreen.h @@ -0,0 +1,52 @@ +/* + * + * Copyright 2013 Canonical Ltd. + * + * 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 SPLASHSCREEN_H +#define SPLASHSCREEN_H + +#include <QtCore> +#include <cplugin.h> + +class Splashscreen: public CPlugin { + Q_OBJECT +public: + explicit Splashscreen(Cordova *cordova); + + virtual const QString fullName() override { + return Splashscreen::fullID(); + } + + virtual const QString shortName() override { + return "SplashScreen"; + } + + static const QString fullID() { + return "SplashScreen"; + } + +public slots: + void show(int, int); + void hide(int, int); +}; + +#endif // SPLASHSCREEN_H diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/wp/ResolutionHelper.cs b/StoneIsland/plugins/cordova-plugin-splashscreen/src/wp/ResolutionHelper.cs new file mode 100644 index 00000000..050c3927 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/wp/ResolutionHelper.cs @@ -0,0 +1,39 @@ +/* + Licensed 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. +*/ + +using Microsoft.Phone.Info; +using System; +using System.Windows; + +namespace WPCordovaClassLib.Cordova.Commands +{ + public enum Resolutions { WVGA, WXGA, HD }; + + public static class ResolutionHelper + { + public static Resolutions CurrentResolution + { + get + { + switch (Application.Current.Host.Content.ScaleFactor) + { + case 100: return Resolutions.WVGA; + case 160: return Resolutions.WXGA; + case 150: return Resolutions.HD; + } + throw new InvalidOperationException("Unknown resolution"); + } + } + } +}
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/src/wp/SplashScreen.cs b/StoneIsland/plugins/cordova-plugin-splashscreen/src/wp/SplashScreen.cs new file mode 100644 index 00000000..680a8058 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/src/wp/SplashScreen.cs @@ -0,0 +1,252 @@ +/* + Licensed 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. +*/ + +using System; +using System.Net; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; +using Microsoft.Phone.Info; +using System.Windows.Controls.Primitives; +using System.Diagnostics; +using System.Windows.Media.Imaging; +using System.Windows.Resources; +using System.IO; +using System.Xml.Linq; +using System.Linq; +using System.Windows.Threading; + +namespace WPCordovaClassLib.Cordova.Commands +{ + /// <summary> + /// Listens for changes to the state of the battery on the device. + /// Currently only the "isPlugged" parameter available via native APIs. + /// </summary> + public class SplashScreen : BaseCommand + { + private Popup popup; + + // Time until we dismiss the splashscreen + private int prefDelay = 3000; + + // Whether we hide it by default + private bool prefAutoHide = true; + + // Path to image to use + private string prefImagePath = "SplashScreenImage.jpg"; + + // static because autodismiss is only ever applied once, at app launch + // subsequent page loads should not cause the SplashScreen to be shown. + private static bool WasShown = false; + + public SplashScreen() + { + LoadConfigPrefs(); + + Image SplashScreen = new Image() + { + Height = Application.Current.Host.Content.ActualHeight, + Width = Application.Current.Host.Content.ActualWidth, + Stretch = Stretch.Fill + }; + + var imageResource = GetSplashScreenImageResource(); + if (imageResource != null) + { + BitmapImage splash_image = new BitmapImage(); + splash_image.SetSource(imageResource.Stream); + SplashScreen.Source = splash_image; + } + + // Instansiate the popup and set the Child property of Popup to SplashScreen + popup = new Popup() { IsOpen = false, + Child = SplashScreen, + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Center + + }; + } + + public override void OnInit() + { + // we only want to autoload on the first page load. + // but OnInit is called for every page load. + if (!SplashScreen.WasShown) + { + SplashScreen.WasShown = true; + show(); + } + } + + private void LoadConfigPrefs() + { + StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("config.xml", UriKind.Relative)); + if (streamInfo != null) + { + using (StreamReader sr = new StreamReader(streamInfo.Stream)) + { + //This will Read Keys Collection for the xml file + XDocument configFile = XDocument.Parse(sr.ReadToEnd()); + + string configAutoHide = configFile.Descendants() + .Where(x => (string)x.Attribute("name") == "AutoHideSplashScreen") + .Select(x => (string)x.Attribute("value")) + .FirstOrDefault(); + + bool bVal; + prefAutoHide = bool.TryParse(configAutoHide, out bVal) ? bVal : prefAutoHide; + + string configDelay = configFile.Descendants() + .Where(x => (string)x.Attribute("name") == "SplashScreenDelay") + .Select(x => (string)x.Attribute("value")) + .FirstOrDefault(); + int nVal; + prefDelay = int.TryParse(configDelay, out nVal) ? nVal : prefDelay; + + string configImage = configFile.Descendants() + .Where(x => (string)x.Attribute("name") == "SplashScreen") + .Select(x => (string)x.Attribute("value")) + .FirstOrDefault(); + + if (!String.IsNullOrEmpty(configImage)) + { + prefImagePath = configImage; + } + } + } + } + + private StreamResourceInfo GetSplashScreenImageResource() + { + // Get the base filename for the splash screen images + string imageName = System.IO.Path.GetFileNameWithoutExtension(prefImagePath); + Uri imageUri = null; + StreamResourceInfo imageResource = null; + + // First, try to get a resolution-specific splashscreen + try + { + // Determine the device's resolution + switch (ResolutionHelper.CurrentResolution) + { + case Resolutions.HD: + imageUri = new Uri(imageName + ".screen-720p.jpg", UriKind.Relative); + break; + + case Resolutions.WVGA: + imageUri = new Uri(imageName + ".screen-WVGA.jpg", UriKind.Relative); + break; + + case Resolutions.WXGA: + default: + imageUri = new Uri(imageName + ".screen-WXGA.jpg", UriKind.Relative); + break; + } + + imageResource = Application.GetResourceStream(imageUri); + } + catch (Exception) + { + // It's OK if we didn't get a resolution-specific image + } + + // Fallback to the default image name without decoration + if (imageResource == null) + { + imageUri = new Uri(prefImagePath, UriKind.Relative); + imageResource = Application.GetResourceStream(imageUri); + } + + if (imageUri != null) Debug.WriteLine("INFO :: SplashScreen: using image {0}", imageUri.OriginalString); + + return imageResource; + } + + public void show(string options = null) + { + Deployment.Current.Dispatcher.BeginInvoke(() => + { + if (!popup.IsOpen) + { + popup.Child.Opacity = 0; + + Storyboard story = new Storyboard(); + DoubleAnimation animation = new DoubleAnimation() + { + From = 0.0, + To = 1.0, + Duration = new Duration(TimeSpan.FromSeconds(0.2)) + }; + + Storyboard.SetTarget(animation, popup.Child); + Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity")); + story.Children.Add(animation); + + story.Begin(); + + popup.IsOpen = true; + + if (prefAutoHide) + { + StartAutoHideTimer(); + } + } + }); + } + + public void hide(string options = null) + { + Deployment.Current.Dispatcher.BeginInvoke(() => + { + if (popup.IsOpen) + { + popup.Child.Opacity = 1.0; + + Storyboard story = new Storyboard(); + DoubleAnimation animation = new DoubleAnimation() + { + From = 1.0, + To = 0.0, + Duration = new Duration(TimeSpan.FromSeconds(0.4)) + }; + + Storyboard.SetTarget(animation, popup.Child); + Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity")); + story.Children.Add(animation); + story.Completed += (object sender, EventArgs e) => + { + popup.IsOpen = false; + }; + story.Begin(); + } + }); + } + + private void StartAutoHideTimer() + { + var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(prefDelay) }; + timer.Tick += (object sender, EventArgs e) => + { + hide(); + timer.Stop(); + }; + timer.Start(); + } + } +} diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/contents.xcworkspacedata b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..2dd325a0 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Workspace + version = "1.0"> + <FileRef + location = "container:CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj"> + </FileRef> +</Workspace> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout new file mode 100644 index 00000000..7e4cdb93 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout @@ -0,0 +1,41 @@ +<?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>IDESourceControlProjectFavoriteDictionaryKey</key> + <false/> + <key>IDESourceControlProjectIdentifier</key> + <string>6BE9AD73-1B9F-4362-98D7-DC631BEC6185</string> + <key>IDESourceControlProjectName</key> + <string>CDVSplashScreenTest</string> + <key>IDESourceControlProjectOriginsDictionary</key> + <dict> + <key>BEF5A5D0FF64801E558286389440357A9233D7DB</key> + <string>https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git</string> + </dict> + <key>IDESourceControlProjectPath</key> + <string>tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj</string> + <key>IDESourceControlProjectRelativeInstallPathDictionary</key> + <dict> + <key>BEF5A5D0FF64801E558286389440357A9233D7DB</key> + <string>../../../../..</string> + </dict> + <key>IDESourceControlProjectURL</key> + <string>https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git</string> + <key>IDESourceControlProjectVersion</key> + <integer>111</integer> + <key>IDESourceControlProjectWCCIdentifier</key> + <string>BEF5A5D0FF64801E558286389440357A9233D7DB</string> + <key>IDESourceControlProjectWCConfigurations</key> + <array> + <dict> + <key>IDESourceControlRepositoryExtensionIdentifierKey</key> + <string>public.vcs.git</string> + <key>IDESourceControlWCCIdentifierKey</key> + <string>BEF5A5D0FF64801E558286389440357A9233D7DB</string> + <key>IDESourceControlWCCName</key> + <string>cordova-plugin-splashscreen</string> + </dict> + </array> +</dict> +</plist> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme new file mode 100644 index 00000000..13f9a157 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest.xcworkspace/xcshareddata/xcschemes/CordovaLib.xcscheme @@ -0,0 +1,77 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Scheme + LastUpgradeVersion = "0600" + version = "1.3"> + <BuildAction + parallelizeBuildables = "YES" + buildImplicitDependencies = "YES"> + <BuildActionEntries> + <BuildActionEntry + buildForTesting = "YES" + buildForRunning = "YES" + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "D2AAC07D0554694100DB518D" + BuildableName = "libCordova.a" + BlueprintName = "CordovaLib" + ReferencedContainer = "container:node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj"> + </BuildableReference> + </BuildActionEntry> + </BuildActionEntries> + </BuildAction> + <TestAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES" + buildConfiguration = "Debug"> + <Testables> + </Testables> + </TestAction> + <LaunchAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Debug" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + allowLocationSimulation = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "D2AAC07D0554694100DB518D" + BuildableName = "libCordova.a" + BlueprintName = "CordovaLib" + ReferencedContainer = "container:node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj"> + </BuildableReference> + </MacroExpansion> + <AdditionalOptions> + </AdditionalOptions> + </LaunchAction> + <ProfileAction + shouldUseLaunchSchemeArgsEnv = "YES" + savedToolIdentifier = "" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Release" + debugDocumentVersioning = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "D2AAC07D0554694100DB518D" + BuildableName = "libCordova.a" + BlueprintName = "CordovaLib" + ReferencedContainer = "container:node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj"> + </BuildableReference> + </MacroExpansion> + </ProfileAction> + <AnalyzeAction + buildConfiguration = "Debug"> + </AnalyzeAction> + <ArchiveAction + buildConfiguration = "Release" + revealArchiveInOrganizer = "YES"> + </ArchiveAction> +</Scheme> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/.npmignore b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/.npmignore new file mode 100644 index 00000000..c795b054 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/.npmignore @@ -0,0 +1 @@ +build
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTest.m b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTest.m new file mode 100644 index 00000000..1637d247 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTest.m @@ -0,0 +1,702 @@ +/* + 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 <XCTest/XCTest.h> +#import <Cordova/CDVScreenOrientationDelegate.h> +#import "CDVSplashScreen.h" +#import "ImageNameTestDelegates.h" + +const CDV_iOSDevice CDV_iOSDeviceZero = { 0, 0, 0, 0, 0, 0 }; + +@interface ImageNameTest : XCTestCase + +@property (nonatomic, strong) CDVSplashScreen* plugin; + +@end + +@interface CDVSplashScreen () + +// expose private interface +- (NSString*)getImageName:(UIInterfaceOrientation)currentOrientation delegate:(id<CDVScreenOrientationDelegate>)orientationDelegate device:(CDV_iOSDevice)device; + +@end + +@implementation ImageNameTest + +- (void)setUp { + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. + + self.plugin = [[CDVSplashScreen alloc] init]; +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void) orientationHelper:(id<CDVScreenOrientationDelegate>)delegate expectedImageNameDictionary:(NSDictionary*)expectedImageNameDictionary device:(CDV_iOSDevice)device{ + + NSString* name = nil; + NSString* expectedImageName = nil; + UIInterfaceOrientation currentOrientation; + NSString* deviceName = device.iPad? @"iPad" : device.iPhone6Plus? @"iPhone6Plus": device.iPhone6? @"iPhone6": device.iPhone5? @"iPhone5" : @"iPhone"; + + // LandscapeLeft, should always return expectedImageName + currentOrientation = UIInterfaceOrientationLandscapeLeft; + name = [self.plugin getImageName:currentOrientation delegate:delegate device:device]; + expectedImageName = [expectedImageNameDictionary objectForKey:@"landscapeLeft"]; + XCTAssertTrue([expectedImageName isEqualToString:name], @"%@ - %@ failed (%@)", @"Landscape", deviceName, name); + + // LandscapeRight - should always return expectedImageName + currentOrientation = UIInterfaceOrientationLandscapeRight; + name = [self.plugin getImageName:currentOrientation delegate:delegate device:device]; + expectedImageName = [expectedImageNameDictionary objectForKey:@"landscapeRight"]; + XCTAssertTrue([expectedImageName isEqualToString:name], @"%@ - %@ failed (%@)", @"Landscape", deviceName, name); + + // Portrait - should always return expectedImageName + currentOrientation = UIInterfaceOrientationPortrait; + name = [self.plugin getImageName:currentOrientation delegate:delegate device:device]; + expectedImageName = [expectedImageNameDictionary objectForKey:@"portrait"]; + XCTAssertTrue([expectedImageName isEqualToString:name], @"%@ - %@ failed (%@)", @"Portrait", deviceName, name); + + // PortraitUpsideDown - should always return expectedImageName + currentOrientation = UIInterfaceOrientationPortraitUpsideDown; + name = [self.plugin getImageName:currentOrientation delegate:delegate device:device]; + expectedImageName = [expectedImageNameDictionary objectForKey:@"portraitUpsideDown"]; + XCTAssertTrue([expectedImageName isEqualToString:name], @"%@ - %@ failed (%@)", @"Portrait", deviceName, name); +} + +- (void)testiPadOrientation { + + CDV_iOSDevice device = CDV_iOSDeviceZero; + device.iPad = YES; + + // One orientation + + PortraitOnly* delegate = [[PortraitOnly alloc] init]; + [self orientationHelper:delegate expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Portrait", + @"landscapeRight" : @"Default-Portrait", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + PortraitUpsideDownOnly* delegate2 = [[PortraitUpsideDownOnly alloc] init]; + [self orientationHelper:delegate2 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Portrait", + @"landscapeRight" : @"Default-Portrait", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + LandscapeLeftOnly* delegate3 = [[LandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate3 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Landscape", + @"portraitUpsideDown" : @"Default-Landscape" + } + device:device]; + + LandscapeRightOnly* delegate4 = [[LandscapeRightOnly alloc] init]; + [self orientationHelper:delegate4 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Landscape", + @"portraitUpsideDown" : @"Default-Landscape" + } + device:device]; + + // All Portrait + + AllPortraitOnly* delegate5 = [[AllPortraitOnly alloc] init]; + [self orientationHelper:delegate5 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Portrait", + @"landscapeRight" : @"Default-Portrait", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + // All Landscape + + AllLandscapeOnly* delegate6 = [[AllLandscapeOnly alloc] init]; + [self orientationHelper:delegate6 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Landscape", + @"portraitUpsideDown" : @"Default-Landscape" + } + device:device]; + + + // All orientations + + AllOrientations* delegate7 = [[AllOrientations alloc] init]; + [self orientationHelper:delegate7 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + // Portrait and Landscape Left + + PortraitAndLandscapeLeftOnly* delegate8 = [[PortraitAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate8 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + // Portrait and Landscape Right + + PortraitAndLandscapeRightOnly* delegate9 = [[PortraitAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate9 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + // PortraitUpsideDown and Landscape Left + + PortraitUpsideDownAndLandscapeLeftOnly* delegate10 = [[PortraitUpsideDownAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate10 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; + + // PortraitUpsideDown and Landscape Right + + PortraitUpsideDownAndLandscapeRightOnly* delegate11 = [[PortraitUpsideDownAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate11 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape", + @"landscapeRight" : @"Default-Landscape", + @"portrait" : @"Default-Portrait", + @"portraitUpsideDown" : @"Default-Portrait" + } + device:device]; +} + +- (void)testiPhoneOrientation { + + CDV_iOSDevice device = CDV_iOSDeviceZero; + device.iPhone = YES; + + // One orientation + + PortraitOnly* delegate = [[PortraitOnly alloc] init]; + [self orientationHelper:delegate expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + PortraitUpsideDownOnly* delegate2 = [[PortraitUpsideDownOnly alloc] init]; + [self orientationHelper:delegate2 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + LandscapeLeftOnly* delegate3 = [[LandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate3 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + LandscapeRightOnly* delegate4 = [[LandscapeRightOnly alloc] init]; + [self orientationHelper:delegate4 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + // All Portrait + + AllPortraitOnly* delegate5 = [[AllPortraitOnly alloc] init]; + [self orientationHelper:delegate5 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + // All Landscape + + AllLandscapeOnly* delegate6 = [[AllLandscapeOnly alloc] init]; + [self orientationHelper:delegate6 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + + // All orientations + + AllOrientations* delegate7 = [[AllOrientations alloc] init]; + [self orientationHelper:delegate7 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + // Portrait and Landscape Left + + PortraitAndLandscapeLeftOnly* delegate8 = [[PortraitAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate8 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + // Portrait and Landscape Right + + PortraitAndLandscapeRightOnly* delegate9 = [[PortraitAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate9 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + // PortraitUpsideDown and Landscape Left + + PortraitUpsideDownAndLandscapeLeftOnly* delegate10 = [[PortraitUpsideDownAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate10 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; + + // PortraitUpsideDown and Landscape Right + + PortraitUpsideDownAndLandscapeRightOnly* delegate11 = [[PortraitUpsideDownAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate11 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default", + @"landscapeRight" : @"Default", + @"portrait" : @"Default", + @"portraitUpsideDown" : @"Default" + } + device:device]; +} + +- (void)testiPhone5Orientation { + + CDV_iOSDevice device = CDV_iOSDeviceZero; + device.iPhone = YES; + device.iPhone5 = YES; + + // One orientation + + PortraitOnly* delegate = [[PortraitOnly alloc] init]; + [self orientationHelper:delegate expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + PortraitUpsideDownOnly* delegate2 = [[PortraitUpsideDownOnly alloc] init]; + [self orientationHelper:delegate2 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + LandscapeLeftOnly* delegate3 = [[LandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate3 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + LandscapeRightOnly* delegate4 = [[LandscapeRightOnly alloc] init]; + [self orientationHelper:delegate4 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + // All Portrait + + AllPortraitOnly* delegate5 = [[AllPortraitOnly alloc] init]; + [self orientationHelper:delegate5 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + // All Landscape + + AllLandscapeOnly* delegate6 = [[AllLandscapeOnly alloc] init]; + [self orientationHelper:delegate6 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + + // All orientations + + AllOrientations* delegate7 = [[AllOrientations alloc] init]; + [self orientationHelper:delegate7 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + // Portrait and Landscape Left + + PortraitAndLandscapeLeftOnly* delegate8 = [[PortraitAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate8 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + // Portrait and Landscape Right + + PortraitAndLandscapeRightOnly* delegate9 = [[PortraitAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate9 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + // PortraitUpsideDown and Landscape Left + + PortraitUpsideDownAndLandscapeLeftOnly* delegate10 = [[PortraitUpsideDownAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate10 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; + + // PortraitUpsideDown and Landscape Right + + PortraitUpsideDownAndLandscapeRightOnly* delegate11 = [[PortraitUpsideDownAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate11 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-568h", + @"landscapeRight" : @"Default-568h", + @"portrait" : @"Default-568h", + @"portraitUpsideDown" : @"Default-568h" + } + device:device]; +} + +- (void)testiPhone6Orientation { + + CDV_iOSDevice device = CDV_iOSDeviceZero; + device.iPhone = YES; + device.iPhone6 = YES; + + // One orientation + + PortraitOnly* delegate = [[PortraitOnly alloc] init]; + [self orientationHelper:delegate expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + PortraitUpsideDownOnly* delegate2 = [[PortraitUpsideDownOnly alloc] init]; + [self orientationHelper:delegate2 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + LandscapeLeftOnly* delegate3 = [[LandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate3 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + LandscapeRightOnly* delegate4 = [[LandscapeRightOnly alloc] init]; + [self orientationHelper:delegate4 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + // All Portrait + + AllPortraitOnly* delegate5 = [[AllPortraitOnly alloc] init]; + [self orientationHelper:delegate5 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + // All Landscape + + AllLandscapeOnly* delegate6 = [[AllLandscapeOnly alloc] init]; + [self orientationHelper:delegate6 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + + // All orientations + + AllOrientations* delegate7 = [[AllOrientations alloc] init]; + [self orientationHelper:delegate7 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + // Portrait and Landscape Left + + PortraitAndLandscapeLeftOnly* delegate8 = [[PortraitAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate8 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + // Portrait and Landscape Right + + PortraitAndLandscapeRightOnly* delegate9 = [[PortraitAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate9 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + // PortraitUpsideDown and Landscape Left + + PortraitUpsideDownAndLandscapeLeftOnly* delegate10 = [[PortraitUpsideDownAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate10 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; + + // PortraitUpsideDown and Landscape Right + + PortraitUpsideDownAndLandscapeRightOnly* delegate11 = [[PortraitUpsideDownAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate11 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-667h", + @"landscapeRight" : @"Default-667h", + @"portrait" : @"Default-667h", + @"portraitUpsideDown" : @"Default-667h" + } + device:device]; +} + +- (void)testiPhone6PlusOrientation { + + CDV_iOSDevice device = CDV_iOSDeviceZero; + device.iPhone = YES; + device.iPhone6Plus = YES; + + // One orientation + + PortraitOnly* delegate = [[PortraitOnly alloc] init]; + [self orientationHelper:delegate expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-736h", + @"landscapeRight" : @"Default-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + PortraitUpsideDownOnly* delegate2 = [[PortraitUpsideDownOnly alloc] init]; + [self orientationHelper:delegate2 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-736h", + @"landscapeRight" : @"Default-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + LandscapeLeftOnly* delegate3 = [[LandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate3 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-Landscape-736h", + @"portraitUpsideDown" : @"Default-Landscape-736h" + } + device:device]; + + LandscapeRightOnly* delegate4 = [[LandscapeRightOnly alloc] init]; + [self orientationHelper:delegate4 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-Landscape-736h", + @"portraitUpsideDown" : @"Default-Landscape-736h" + } + device:device]; + + // All Portrait + + AllPortraitOnly* delegate5 = [[AllPortraitOnly alloc] init]; + [self orientationHelper:delegate5 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-736h", + @"landscapeRight" : @"Default-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + // All Landscape + + AllLandscapeOnly* delegate6 = [[AllLandscapeOnly alloc] init]; + [self orientationHelper:delegate6 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-Landscape-736h", + @"portraitUpsideDown" : @"Default-Landscape-736h" + } + device:device]; + + + // All orientations + + AllOrientations* delegate7 = [[AllOrientations alloc] init]; + [self orientationHelper:delegate7 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + // Portrait and Landscape Left + + PortraitAndLandscapeLeftOnly* delegate8 = [[PortraitAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate8 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + // Portrait and Landscape Right + + PortraitAndLandscapeRightOnly* delegate9 = [[PortraitAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate9 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + // PortraitUpsideDown and Landscape Left + + PortraitUpsideDownAndLandscapeLeftOnly* delegate10 = [[PortraitUpsideDownAndLandscapeLeftOnly alloc] init]; + [self orientationHelper:delegate10 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; + + // PortraitUpsideDown and Landscape Right + + PortraitUpsideDownAndLandscapeRightOnly* delegate11 = [[PortraitUpsideDownAndLandscapeRightOnly alloc] init]; + [self orientationHelper:delegate11 expectedImageNameDictionary:@{ + @"landscapeLeft" : @"Default-Landscape-736h", + @"landscapeRight" : @"Default-Landscape-736h", + @"portrait" : @"Default-736h", + @"portraitUpsideDown" : @"Default-736h" + } + device:device]; +} + + + +@end diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.h b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.h new file mode 100644 index 00000000..be4a7883 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.h @@ -0,0 +1,57 @@ +/* + 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/CDVScreenOrientationDelegate.h> + +@interface PortraitOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface PortraitUpsideDownOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface AllPortraitOnly : NSObject <CDVScreenOrientationDelegate> +@end + + +@interface LandscapeLeftOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface LandscapeRightOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface AllLandscapeOnly : NSObject <CDVScreenOrientationDelegate> +@end + + +@interface AllOrientations : NSObject <CDVScreenOrientationDelegate> +@end + +@interface PortraitAndLandscapeLeftOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface PortraitAndLandscapeRightOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface PortraitUpsideDownAndLandscapeLeftOnly : NSObject <CDVScreenOrientationDelegate> +@end + +@interface PortraitUpsideDownAndLandscapeRightOnly : NSObject <CDVScreenOrientationDelegate> +@end + diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.m b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.m new file mode 100644 index 00000000..b5a1b23e --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/ImageNameTestDelegates.m @@ -0,0 +1,200 @@ +/* + 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 "ImageNameTestDelegates.h" + +@implementation PortraitOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortrait; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation PortraitUpsideDownOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortraitUpsideDown; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation AllPortraitOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + + +@implementation LandscapeLeftOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskLandscapeLeft; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation LandscapeRightOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskLandscapeRight; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation AllLandscapeOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + + +@implementation AllOrientations + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskAll; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation PortraitAndLandscapeLeftOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation PortraitAndLandscapeRightOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeRight; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation PortraitUpsideDownAndLandscapeLeftOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortraitUpsideDown | UIInterfaceOrientationMaskLandscapeLeft; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + +@implementation PortraitUpsideDownAndLandscapeRightOnly + +- (NSUInteger)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskPortraitUpsideDown | UIInterfaceOrientationMaskLandscapeRight; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return [self supportedInterfaceOrientations] & (1 << interfaceOrientation) ; +} + +- (BOOL)shouldAutorotate { + return YES; +} + +@end + diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/Info.plist b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/Info.plist new file mode 100644 index 00000000..95c8addb --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenLibTests/Info.plist @@ -0,0 +1,44 @@ +<?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"> +<!-- +# +# 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> + <key>CFBundleDevelopmentRegion</key> + <string>en</string> + <key>CFBundleExecutable</key> + <string>$(EXECUTABLE_NAME)</string> + <key>CFBundleIdentifier</key> + <string>org.apache.cordova.$(PRODUCT_NAME:rfc1034identifier)</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>$(PRODUCT_NAME)</string> + <key>CFBundlePackageType</key> + <string>BNDL</string> + <key>CFBundleShortVersionString</key> + <string>1.0</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>1</string> +</dict> +</plist> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.pbxproj b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.pbxproj new file mode 100644 index 00000000..ce820d81 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.pbxproj @@ -0,0 +1,505 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 7E9F51AB19DA10AE00DA31AC /* CDVSplashScreen.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E9F51A919DA10AE00DA31AC /* CDVSplashScreen.m */; }; + 7E9F51B119DA114400DA31AC /* ImageNameTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E9F51B019DA114400DA31AC /* ImageNameTest.m */; }; + 7E9F51B319DA116500DA31AC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7E9F51B219DA116500DA31AC /* Foundation.framework */; }; + 7E9F51B519DA127E00DA31AC /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7E9F51B419DA127E00DA31AC /* UIKit.framework */; }; + 7E9F51B819DA14FD00DA31AC /* ImageNameTestDelegates.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E9F51B719DA14FD00DA31AC /* ImageNameTestDelegates.m */; }; + 7E9F51B919DA1B1600DA31AC /* libCDVSplashScreenLib.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7E9F519519DA102000DA31AC /* libCDVSplashScreenLib.a */; }; + 7E9F51BA19DA1B2000DA31AC /* libCordova.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7E9F519019DA0F8300DA31AC /* libCordova.a */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 7E9F518F19DA0F8300DA31AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 68A32D7114102E1C006B237C; + remoteInfo = CordovaLib; + }; + 7E9F51AC19DA10DE00DA31AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7E9F517219DA09CE00DA31AC /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7E9F519419DA102000DA31AC; + remoteInfo = CDVSplashScreenLib; + }; + 7E9F51AE19DA10E100DA31AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = D2AAC07D0554694100DB518D; + remoteInfo = CordovaLib; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 7E9F519319DA102000DA31AC /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = CordovaLib.xcodeproj; path = "../node_modules/cordova-ios/CordovaLib/CordovaLib.xcodeproj"; sourceTree = "<group>"; }; + 7E9F519519DA102000DA31AC /* libCDVSplashScreenLib.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libCDVSplashScreenLib.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 7E9F519F19DA102000DA31AC /* CDVSplashScreenLibTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CDVSplashScreenLibTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 7E9F51A219DA102000DA31AC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; + 7E9F51A919DA10AE00DA31AC /* CDVSplashScreen.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVSplashScreen.m; path = ../../../src/ios/CDVSplashScreen.m; sourceTree = SOURCE_ROOT; }; + 7E9F51AA19DA10AE00DA31AC /* CDVSplashScreen.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVSplashScreen.h; path = ../../../src/ios/CDVSplashScreen.h; sourceTree = SOURCE_ROOT; }; + 7E9F51B019DA114400DA31AC /* ImageNameTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ImageNameTest.m; sourceTree = "<group>"; }; + 7E9F51B219DA116500DA31AC /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 7E9F51B419DA127E00DA31AC /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 7E9F51B619DA12C600DA31AC /* ImageNameTestDelegates.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImageNameTestDelegates.h; sourceTree = "<group>"; }; + 7E9F51B719DA14FD00DA31AC /* ImageNameTestDelegates.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ImageNameTestDelegates.m; sourceTree = "<group>"; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 7E9F519219DA102000DA31AC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7E9F519C19DA102000DA31AC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E9F51BA19DA1B2000DA31AC /* libCordova.a in Frameworks */, + 7E9F51B919DA1B1600DA31AC /* libCDVSplashScreenLib.a in Frameworks */, + 7E9F51B519DA127E00DA31AC /* UIKit.framework in Frameworks */, + 7E9F51B319DA116500DA31AC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 7E9F517119DA09CE00DA31AC = { + isa = PBXGroup; + children = ( + 7E9F51B419DA127E00DA31AC /* UIKit.framework */, + 7E9F51B219DA116500DA31AC /* Foundation.framework */, + 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */, + 7E9F519619DA102000DA31AC /* CDVSplashScreenLib */, + 7E9F51A019DA102000DA31AC /* CDVSplashScreenLibTests */, + 7E9F517D19DA0A0A00DA31AC /* Products */, + ); + sourceTree = "<group>"; + }; + 7E9F517D19DA0A0A00DA31AC /* Products */ = { + isa = PBXGroup; + children = ( + 7E9F519519DA102000DA31AC /* libCDVSplashScreenLib.a */, + 7E9F519F19DA102000DA31AC /* CDVSplashScreenLibTests.xctest */, + ); + name = Products; + sourceTree = "<group>"; + }; + 7E9F518C19DA0F8300DA31AC /* Products */ = { + isa = PBXGroup; + children = ( + 7E9F519019DA0F8300DA31AC /* libCordova.a */, + ); + name = Products; + sourceTree = "<group>"; + }; + 7E9F519619DA102000DA31AC /* CDVSplashScreenLib */ = { + isa = PBXGroup; + children = ( + 7E9F51A919DA10AE00DA31AC /* CDVSplashScreen.m */, + 7E9F51AA19DA10AE00DA31AC /* CDVSplashScreen.h */, + ); + path = CDVSplashScreenLib; + sourceTree = SOURCE_ROOT; + }; + 7E9F51A019DA102000DA31AC /* CDVSplashScreenLibTests */ = { + isa = PBXGroup; + children = ( + 7E9F51A119DA102000DA31AC /* Supporting Files */, + 7E9F51B019DA114400DA31AC /* ImageNameTest.m */, + 7E9F51B619DA12C600DA31AC /* ImageNameTestDelegates.h */, + 7E9F51B719DA14FD00DA31AC /* ImageNameTestDelegates.m */, + ); + path = CDVSplashScreenLibTests; + sourceTree = "<group>"; + }; + 7E9F51A119DA102000DA31AC /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 7E9F51A219DA102000DA31AC /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = "<group>"; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 7E9F519419DA102000DA31AC /* CDVSplashScreenLib */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7E9F51A319DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVSplashScreenLib" */; + buildPhases = ( + 7E9F519119DA102000DA31AC /* Sources */, + 7E9F519219DA102000DA31AC /* Frameworks */, + 7E9F519319DA102000DA31AC /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = CDVSplashScreenLib; + productName = CDVSplashScreenLib; + productReference = 7E9F519519DA102000DA31AC /* libCDVSplashScreenLib.a */; + productType = "com.apple.product-type.library.static"; + }; + 7E9F519E19DA102000DA31AC /* CDVSplashScreenLibTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7E9F51A619DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVSplashScreenLibTests" */; + buildPhases = ( + 7E9F519B19DA102000DA31AC /* Sources */, + 7E9F519C19DA102000DA31AC /* Frameworks */, + 7E9F519D19DA102000DA31AC /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 7E9F51AF19DA10E100DA31AC /* PBXTargetDependency */, + 7E9F51AD19DA10DE00DA31AC /* PBXTargetDependency */, + ); + name = CDVSplashScreenLibTests; + productName = CDVSplashScreenLibTests; + productReference = 7E9F519F19DA102000DA31AC /* CDVSplashScreenLibTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 7E9F517219DA09CE00DA31AC /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0600; + TargetAttributes = { + 7E9F519419DA102000DA31AC = { + CreatedOnToolsVersion = 6.0; + }; + 7E9F519E19DA102000DA31AC = { + CreatedOnToolsVersion = 6.0; + }; + }; + }; + buildConfigurationList = 7E9F517519DA09CE00DA31AC /* Build configuration list for PBXProject "CDVSplashScreenTest" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7E9F517119DA09CE00DA31AC; + productRefGroup = 7E9F517D19DA0A0A00DA31AC /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 7E9F518C19DA0F8300DA31AC /* Products */; + ProjectRef = 7E9F518B19DA0F8300DA31AC /* CordovaLib.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 7E9F519419DA102000DA31AC /* CDVSplashScreenLib */, + 7E9F519E19DA102000DA31AC /* CDVSplashScreenLibTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 7E9F519019DA0F8300DA31AC /* libCordova.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libCordova.a; + remoteRef = 7E9F518F19DA0F8300DA31AC /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 7E9F519D19DA102000DA31AC /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 7E9F519119DA102000DA31AC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E9F51AB19DA10AE00DA31AC /* CDVSplashScreen.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7E9F519B19DA102000DA31AC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E9F51B119DA114400DA31AC /* ImageNameTest.m in Sources */, + 7E9F51B819DA14FD00DA31AC /* ImageNameTestDelegates.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 7E9F51AD19DA10DE00DA31AC /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 7E9F519419DA102000DA31AC /* CDVSplashScreenLib */; + targetProxy = 7E9F51AC19DA10DE00DA31AC /* PBXContainerItemProxy */; + }; + 7E9F51AF19DA10E100DA31AC /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CordovaLib; + targetProxy = 7E9F51AE19DA10E100DA31AC /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 7E9F517619DA09CE00DA31AC /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + }; + name = Debug; + }; + 7E9F517719DA09CE00DA31AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + }; + name = Release; + }; + 7E9F51A419DA102000DA31AC /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + 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; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"$(TARGET_BUILD_DIR)/usr/local/lib/include\"", + "\"$(OBJROOT)/UninstalledProducts/include\"", + "\"$(BUILT_PRODUCTS_DIR)\"", + ); + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 7E9F51A519DA102000DA31AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + 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; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"$(TARGET_BUILD_DIR)/usr/local/lib/include\"", + "\n\"$(OBJROOT)/UninstalledProducts/include\"\n\"$(BUILT_PRODUCTS_DIR)\"", + ); + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 7E9F51A719DA102000DA31AC /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + 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; + INFOPLIST_FILE = CDVSplashScreenLibTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + }; + name = Debug; + }; + 7E9F51A819DA102000DA31AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + 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; + INFOPLIST_FILE = CDVSplashScreenLibTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 7E9F517519DA09CE00DA31AC /* Build configuration list for PBXProject "CDVSplashScreenTest" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7E9F517619DA09CE00DA31AC /* Debug */, + 7E9F517719DA09CE00DA31AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7E9F51A319DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVSplashScreenLib" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7E9F51A419DA102000DA31AC /* Debug */, + 7E9F51A519DA102000DA31AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7E9F51A619DA102000DA31AC /* Build configuration list for PBXNativeTarget "CDVSplashScreenLibTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7E9F51A719DA102000DA31AC /* Debug */, + 7E9F51A819DA102000DA31AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 7E9F517219DA09CE00DA31AC /* Project object */; +} diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..8f912784 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Workspace + version = "1.0"> + <FileRef + location = "self:CDVSplashScreenTest.xcodeproj"> + </FileRef> +</Workspace> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout new file mode 100644 index 00000000..7e4cdb93 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/project.xcworkspace/xcshareddata/CDVSplashScreenTest.xccheckout @@ -0,0 +1,41 @@ +<?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>IDESourceControlProjectFavoriteDictionaryKey</key> + <false/> + <key>IDESourceControlProjectIdentifier</key> + <string>6BE9AD73-1B9F-4362-98D7-DC631BEC6185</string> + <key>IDESourceControlProjectName</key> + <string>CDVSplashScreenTest</string> + <key>IDESourceControlProjectOriginsDictionary</key> + <dict> + <key>BEF5A5D0FF64801E558286389440357A9233D7DB</key> + <string>https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git</string> + </dict> + <key>IDESourceControlProjectPath</key> + <string>tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj</string> + <key>IDESourceControlProjectRelativeInstallPathDictionary</key> + <dict> + <key>BEF5A5D0FF64801E558286389440357A9233D7DB</key> + <string>../../../../..</string> + </dict> + <key>IDESourceControlProjectURL</key> + <string>https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git</string> + <key>IDESourceControlProjectVersion</key> + <integer>111</integer> + <key>IDESourceControlProjectWCCIdentifier</key> + <string>BEF5A5D0FF64801E558286389440357A9233D7DB</string> + <key>IDESourceControlProjectWCConfigurations</key> + <array> + <dict> + <key>IDESourceControlRepositoryExtensionIdentifierKey</key> + <string>public.vcs.git</string> + <key>IDESourceControlWCCIdentifierKey</key> + <string>BEF5A5D0FF64801E558286389440357A9233D7DB</string> + <key>IDESourceControlWCCName</key> + <string>cordova-plugin-splashscreen</string> + </dict> + </array> +</dict> +</plist> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLib.xcscheme b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLib.xcscheme new file mode 100644 index 00000000..b97b8633 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLib.xcscheme @@ -0,0 +1,77 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Scheme + LastUpgradeVersion = "0600" + version = "1.3"> + <BuildAction + parallelizeBuildables = "YES" + buildImplicitDependencies = "YES"> + <BuildActionEntries> + <BuildActionEntry + buildForTesting = "YES" + buildForRunning = "YES" + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519419DA102000DA31AC" + BuildableName = "libCDVSplashScreenLib.a" + BlueprintName = "CDVSplashScreenLib" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </BuildActionEntry> + </BuildActionEntries> + </BuildAction> + <TestAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES" + buildConfiguration = "Debug"> + <Testables> + </Testables> + </TestAction> + <LaunchAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Debug" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + allowLocationSimulation = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519419DA102000DA31AC" + BuildableName = "libCDVSplashScreenLib.a" + BlueprintName = "CDVSplashScreenLib" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </MacroExpansion> + <AdditionalOptions> + </AdditionalOptions> + </LaunchAction> + <ProfileAction + shouldUseLaunchSchemeArgsEnv = "YES" + savedToolIdentifier = "" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Release" + debugDocumentVersioning = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519419DA102000DA31AC" + BuildableName = "libCDVSplashScreenLib.a" + BlueprintName = "CDVSplashScreenLib" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </MacroExpansion> + </ProfileAction> + <AnalyzeAction + buildConfiguration = "Debug"> + </AnalyzeAction> + <ArchiveAction + buildConfiguration = "Release" + revealArchiveInOrganizer = "YES"> + </ArchiveAction> +</Scheme> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLibTests.xcscheme b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLibTests.xcscheme new file mode 100644 index 00000000..6a2a5261 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/CDVSplashScreenTest/CDVSplashScreenTest.xcodeproj/xcshareddata/xcschemes/CDVSplashScreenLibTests.xcscheme @@ -0,0 +1,96 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Scheme + LastUpgradeVersion = "0600" + version = "1.3"> + <BuildAction + parallelizeBuildables = "YES" + buildImplicitDependencies = "YES"> + <BuildActionEntries> + <BuildActionEntry + buildForTesting = "YES" + buildForRunning = "YES" + buildForProfiling = "NO" + buildForArchiving = "NO" + buildForAnalyzing = "YES"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519E19DA102000DA31AC" + BuildableName = "CDVSplashScreenLibTests.xctest" + BlueprintName = "CDVSplashScreenLibTests" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </BuildActionEntry> + </BuildActionEntries> + </BuildAction> + <TestAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES" + buildConfiguration = "Debug"> + <Testables> + <TestableReference + skipped = "NO"> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519E19DA102000DA31AC" + BuildableName = "CDVSplashScreenLibTests.xctest" + BlueprintName = "CDVSplashScreenLibTests" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </TestableReference> + </Testables> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519E19DA102000DA31AC" + BuildableName = "CDVSplashScreenLibTests.xctest" + BlueprintName = "CDVSplashScreenLibTests" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </MacroExpansion> + </TestAction> + <LaunchAction + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Debug" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + allowLocationSimulation = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519E19DA102000DA31AC" + BuildableName = "CDVSplashScreenLibTests.xctest" + BlueprintName = "CDVSplashScreenLibTests" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </MacroExpansion> + <AdditionalOptions> + </AdditionalOptions> + </LaunchAction> + <ProfileAction + shouldUseLaunchSchemeArgsEnv = "YES" + savedToolIdentifier = "" + useCustomWorkingDirectory = "NO" + buildConfiguration = "Release" + debugDocumentVersioning = "YES"> + <MacroExpansion> + <BuildableReference + BuildableIdentifier = "primary" + BlueprintIdentifier = "7E9F519E19DA102000DA31AC" + BuildableName = "CDVSplashScreenLibTests.xctest" + BlueprintName = "CDVSplashScreenLibTests" + ReferencedContainer = "container:CDVSplashScreenTest.xcodeproj"> + </BuildableReference> + </MacroExpansion> + </ProfileAction> + <AnalyzeAction + buildConfiguration = "Debug"> + </AnalyzeAction> + <ArchiveAction + buildConfiguration = "Release" + revealArchiveInOrganizer = "YES"> + </ArchiveAction> +</Scheme> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/README.md new file mode 100644 index 00000000..97ee9dff --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/README.md @@ -0,0 +1,40 @@ +<!-- +# license: 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. +--> + +# iOS Tests for CDVSplashScreen + +You need to install `node.js` to pull in `cordova-ios`. + +First install cordova-ios: + + npm install + +... in the current folder. + + +# Testing from Xcode + +1. Launch the `CDVSplashScreenTest.xcworkspace` file. +2. Choose "CDVSplashScreenLibTests" from the scheme drop-down menu +3. Click and hold on the `Play` button, and choose the `Wrench` icon to run the tests + + +# Testing from the command line + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/de/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/de/README.md new file mode 100644 index 00000000..9c7f0a4f --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/de/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# iOS-Tests für CDVSplashScreen + +Sie müssen installieren `node.js` in `Cordova-Ios` zu ziehen. + +Installieren Sie Cordova-Ios zum ersten Mal: + + npm install + + +... im aktuellen Ordner. + +# Testen von Xcode + + 1. Starten Sie die Datei `CDVSplashScreenTest.xcworkspace` . + 2. Wählen Sie im Dropdown-Schema "CDVSplashScreenLibTests" + 3. Klicken Sie und halten Sie auf den `Play` -Button und wählen Sie das `Schraubenschlüssel` -Symbol zum Ausführen der tests + +# Tests von der Befehlszeile aus + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/es/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/es/README.md new file mode 100644 index 00000000..2176c921 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/es/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# Pruebas de iOS para CDVSplashScreen + +Necesita instalar `node.js` en `Córdoba-ios`. + +Primero instalar cordova-ios: + + npm install + + +... en la carpeta actual. + +# Prueba de Xcode + + 1. Iniciar el archivo `CDVSplashScreenTest.xcworkspace` . + 2. Elija "CDVSplashScreenLibTests" en el menú de lista desplegable esquema + 3. Haga clic y mantenga el botón de `Play` y elegir el icono de `llave inglesa` para ejecutar las pruebas + +# Pruebas desde la lÃnea de comandos + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/fr/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/fr/README.md new file mode 100644 index 00000000..0dbbd0d2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/fr/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# Tests d'iOS pour CDVSplashScreen + +Vous devez installer `node.js` à `cordova-ios`. + +Commencez par installer cordova-ios : + + npm install + + +... dans le dossier actuel. + +# Tests de Xcode + + 1. Lancez le fichier `CDVSplashScreenTest.xcworkspace` . + 2. Choisissez « CDVSplashScreenLibTests » dans le menu déroulant de régime + 3. Cliquez et maintenez sur la touche `Play` et cliquez sur l'icône de `clé` pour exécuter les tests + +# Test de la ligne de commande + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/it/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/it/README.md new file mode 100644 index 00000000..2a42df67 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/it/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# Test di iOS per CDVSplashScreen + +È necessario installare `node. js` per tirare in `cordova-ios`. + +In primo luogo installare cordova-ios: + + npm install + + +... nella cartella corrente. + +# Test da Xcode + + 1. Lanciare il file `CDVSplashScreenTest.xcworkspace` . + 2. Scegli "CDVSplashScreenLibTests" dal menu a discesa Schema + 3. Fare clic e tenere premuto il pulsante `Play` e scegliere l'icona della `chiave inglese` per eseguire i test + +# Test dalla riga di comando + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/ja/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/ja/README.md new file mode 100644 index 00000000..011b8242 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/ja/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# CDVSplashScreen ã® iOS ã®ãƒ†ã‚¹ãƒˆ + +`Node.js` `コルドãƒ`ios をプルã™ã‚‹ã‚’インストールã™ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚. + +コルドムios をインストールã—ã¾ã™ã€‚ + + npm install + + +ç¾åœ¨ã®ãƒ•ォルダーã«. + +# Xcode ã‹ã‚‰ãƒ†ã‚¹ãƒˆ + + 1. `CDVSplashScreenTest.xcworkspace`ファイルを起動ã—ã¾ã™ã€‚ + 2. スã‚ーム] ドãƒãƒƒãƒ—ダウン メニューã‹ã‚‰"CDVSplashScreenLibTests"ã‚’é¸æŠžã—ã¾ã™ã€‚ + 3. クリックã—ã€`å†ç”Ÿ`ボタンを押ã—ã€ãƒ†ã‚¹ãƒˆã‚’実行ã™ã‚‹`レンãƒ`ã®ã‚¢ã‚¤ã‚³ãƒ³ã‚’é¸æŠž + +# コマンドラインã‹ã‚‰ãƒ†ã‚¹ãƒˆ + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/ko/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/ko/README.md new file mode 100644 index 00000000..6981207a --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/ko/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# CDVSplashScreenì— ëŒ€ 한 iOS 테스트 + +`Node.js` `코르ë„ë°”` iosì—서를 설치 해야. + +코르ë„ë°”-ios를 설치 하는 첫번째는: + + npm install + + +현재 í´ë”ì—.... + +# Xcodeì—서 테스트 + + 1. `CDVSplashScreenTest.xcworkspace` 파ì¼ì„ 시작 합니다. + 2. 구성표 ë“œë¡ ë‹¤ìš´ 메뉴ì—서 "CDVSplashScreenLibTests"를 ì„ íƒ + 3. í´ë¦ 하 ê³ `재ìƒ` 버튼ì—는 테스트를 실행 í•˜ë ¤ë©´ `공구 모양` ì•„ì´ì½˜ì„ ì„ íƒ + +# ëª…ë ¹ì¤„ì—서 테스트 + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/pl/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/pl/README.md new file mode 100644 index 00000000..f13828fe --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/pl/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# iOS testy dla CDVSplashScreen + +Musisz zainstalować `node.js` ciÄ…gnąć w `cordova-ios`. + +Najpierw zainstalować cordova-ios: + + npm install + + +... w folderze bieżącym. + +# Badania z Xcode + + 1. Uruchom plik `CDVSplashScreenTest.xcworkspace` . + 2. Wybierz z menu rozwijanego systemu "CDVSplashScreenLibTests" + 3. Kliknij i przytrzymaj przycisk `Play` i wybrać ikonÄ™ `klucz` do testów + +# Badania z wiersza polecenia + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/zh/README.md b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/zh/README.md new file mode 100644 index 00000000..3a04bcd1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/doc/zh/README.md @@ -0,0 +1,39 @@ +<!-- +# license: 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. +--> + +# CDVSplashScreen çš„ iOS 測試 + +您需è¦å®‰è£`node.js`拉`科爾多瓦 ios`ä¸. + +第一次安è£ç§‘爾多瓦 ios: + + npm install + + +在當å‰è³‡æ–™å¤¾ä¸ã€‚ + +# 從 Xcode 測試 + + 1. 啟動`CDVSplashScreenTest.xcworkspace`檔。 + 2. 從方案下拉å¼åŠŸèƒ½è¡¨ä¸é¸æ“‡"CDVSplashScreenLibTests" + 3. æŒ‰ä¸€ä¸‹ä¸¦å …æŒ`æ’æ”¾`æŒ‰éˆ•ï¼Œç„¶å¾Œé¸æ“‡è¦é‹è¡Œçš„æ¸¬è©¦çš„`扳手`圖示 + +# 從命令列測試 + + npm test diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/package.json b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/package.json new file mode 100644 index 00000000..d8b23857 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/ios/package.json @@ -0,0 +1,13 @@ +{ + "name": "cordova-plugin-splashscreen-test-ios", + "version": "1.0.0", + "description": "iOS Unit Tests for Splashscreen Plugin", + "author": "Apache Software Foundation", + "license": "Apache Version 2.0", + "dependencies": { + "cordova-ios": "^3.6.0" + }, + "scripts": { + "test": "xcodebuild test -workspace CDVSplashScreenTest.xcworkspace -scheme CDVSplashScreenLibTests -destination 'platform=iOS Simulator,name=iPhone 5' CONFIGURATION_BUILD_DIR='/tmp'" + } +}
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/plugin.xml b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/plugin.xml new file mode 100644 index 00000000..bf9cb0ac --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/plugin.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="cordova-plugin-splashscreen-tests" + version="2.1.0"> + <name>Cordova Splashscreen Plugin Tests</name> + <license>Apache 2.0</license> + + <js-module src="tests.js" name="tests"> + </js-module> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/tests/tests.js b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/tests.js new file mode 100644 index 00000000..8c4d22b4 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/tests/tests.js @@ -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. + * +*/ + +exports.defineAutoTest = function () { + describe('Splashscreen (cordova)', function () { + it("splashscreen.spec.1 should exist", function () { + expect(navigator.splashscreen).toBeDefined(); + }); + + it("splashscreen.spec.2 exec method should exist", function () { + expect(navigator.splashscreen.show).toBeDefined(); + expect(typeof navigator.splashscreen.show).toBe('function'); + }); + + it("splashscreen.spec.3 exec method should exist", function () { + expect(navigator.splashscreen.hide).toBeDefined(); + expect(typeof navigator.splashscreen.hide).toBe('function'); + }); + }); +}; + +exports.defineManualTests = function (contentEl, createActionButton) { + function showFor(duration) { + navigator.splashscreen.show(); + window.setTimeout(function () { + navigator.splashscreen.hide(); + }, 1000 * duration); + } + + contentEl.innerHTML = '<h1>Splashscreen Tests</h1>' + + '<h3>Note for WP: AutoHideSplashScreen must be set to false in config.xml</h3>' + + '<div id="show1"></div>' + + 'Expected result: Will show the Cordova splashscreen for 1 second' + + '</p> <div id="show5"></div>' + + 'Expected result: Will show the Cordova splashscreen for 5 seconds'; + + createActionButton('Show for 1 second', function () { + showFor(1); + }, 'show1'); + + createActionButton('Show for 5 seconds', function () { + showFor(5); + }, 'show5'); +}; diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/www/splashscreen.js b/StoneIsland/plugins/cordova-plugin-splashscreen/www/splashscreen.js new file mode 100644 index 00000000..7cb48bdd --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/www/splashscreen.js @@ -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. + * +*/ + +var exec = require('cordova/exec'); + +var splashscreen = { + show:function() { + exec(null, null, "SplashScreen", "show", []); + }, + hide:function() { + exec(null, null, "SplashScreen", "hide", []); + } +}; + +module.exports = splashscreen; diff --git a/StoneIsland/plugins/cordova-plugin-splashscreen/www/windows/SplashScreenProxy.js b/StoneIsland/plugins/cordova-plugin-splashscreen/www/windows/SplashScreenProxy.js new file mode 100644 index 00000000..dab72381 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-splashscreen/www/windows/SplashScreenProxy.js @@ -0,0 +1,77 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/*jslint sloppy:true */ +/*global Windows:true, require, module, window, document, WinJS */ + +var cordova = require('cordova'), + channel = require('cordova/channel'); + +var isPhone = (cordova.platformId == "windows") && WinJS.Utilities.isPhone; +var localSplash = null; +var bgColor = "#464646"; // default backgrond color; TDOO - read it from .appxmanifest +var splashImageSrc = isPhone ? "ms-appx:///images/splashscreenphone.png" : "ms-appx:///images/splashscreen.png"; + +var SplashScreen = { + setBGColor: function (cssBGColor) { + bgColor = cssBGColor; + if (localSplash) { + localSplash.style.backgroundColor = bgColor; + } + }, + show: function () { + if (localSplash) { + return; // already showed + } + + localSplash = document.createElement("div"); + localSplash.style.backgroundColor = bgColor; + localSplash.style.position = "fixed"; + localSplash.style.top = "0"; + localSplash.style.width = "100%"; + localSplash.style.height = "100%"; + + localSplashImage = document.createElement("img"); + localSplashImage.src = splashImageSrc; + localSplashImage.style.maxWidth = "100%"; + localSplashImage.style.maxHeight = "100%"; + // center horizontally + localSplashImage.style.margin = "0 auto"; + localSplashImage.style.display = "block"; + // center vertically + localSplashImage.style.position = "relative"; + localSplashImage.style.top = "50%"; + localSplashImage.style.transform = "translateY(-50%)"; + + localSplash.appendChild(localSplashImage); + document.body.appendChild(localSplash); + }, + hide: function () { + if (localSplash) { + document.body.removeChild(localSplash); + localSplash = null; + } + } +}; + +module.exports = SplashScreen; + +require("cordova/exec/proxy").add("SplashScreen", SplashScreen); diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/CONTRIBUTING.md b/StoneIsland/plugins/cordova-plugin-whitelist/CONTRIBUTING.md new file mode 100644 index 00000000..e4a178f5 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/CONTRIBUTING.md @@ -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. +# +--> + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/#contribute). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/LICENSE b/StoneIsland/plugins/cordova-plugin-whitelist/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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.
\ No newline at end of file diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/NOTICE b/StoneIsland/plugins/cordova-plugin-whitelist/NOTICE new file mode 100644 index 00000000..8ec56a52 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/README.md b/StoneIsland/plugins/cordova-plugin-whitelist/README.md new file mode 100644 index 00000000..def10044 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/README.md @@ -0,0 +1,144 @@ +<!--- + license: 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-plugin-whitelist + +This plugin implements a whitelist policy for navigating the application webview on Cordova 4.0 + +## Supported Cordova Platforms + +* Android 4.0.0 or above +* iOS 4.0.0 or above + +## Navigation Whitelist +Controls which URLs the WebView itself can be navigated to. Applies to +top-level navigations only. + +Quirks: on Android it also applies to iframes for non-http(s) schemes. + +By default, navigations only to `file://` URLs, are allowed. To allow other +other URLs, you must add `<allow-navigation>` tags to your `config.xml`: + + <!-- Allow links to example.com --> + <allow-navigation href="http://example.com/*" /> + + <!-- Wildcards are allowed for the protocol, as a prefix + to the host, or as a suffix to the path --> + <allow-havigation href="*://*.example.com/*" /> + + <!-- A wildcard can be used to whitelist the entire network, + over HTTP and HTTPS. + *NOT RECOMMENDED* --> + <allow-navigation href="*" /> + + <!-- The above is equivalent to these three declarations --> + <allow-navigation href="http://*/*" /> + <allow-navigation href="https://*/*" /> + <allow-navigation href="data:*" /> + +## Intent Whitelist +Controls which URLs the app is allowed to ask the system to open. +By default, no external URLs are allowed. + +On Android, this equates to sending an intent of type BROWSEABLE. + +This whitelist does not apply to plugins, only hyperlinks and calls to `window.open()`. + +In `config.xml`, add `<allow-intent>` tags, like this: + + <!-- Allow links to web pages to open in a browser --> + <allow-intent href="http://*/*" /> + <allow-intent href="https://*/*" /> + + <!-- Allow links to example.com to open in a browser --> + <allow-intent href="http://example.com/*" /> + + <!-- Wildcards are allowed for the protocol, as a prefix + to the host, or as a suffix to the path --> + <allow-intent href="*://*.example.com/*" /> + + <!-- Allow SMS links to open messaging app --> + <allow-intent href="sms:*" /> + + <!-- Allow tel: links to open the dialer --> + <allow-intent href="tel:*" /> + + <!-- Allow geo: links to open maps --> + <allow-intent href="geo:*" /> + + <!-- Allow all unrecognized URLs to open installed apps + *NOT RECOMMENDED* --> + <allow-intent href="*" /> + +## Network Request Whitelist +Controls which network requests (images, XHRs, etc) are allowed to be made (via cordova native hooks). + +Note: We suggest you use a Content Security Policy (see below), which is more secure. This whitelist is mostly historical for webviews which do not support CSP. + +In `config.xml`, add `<access>` tags, like this: + + <!-- Allow images, xhrs, etc. to google.com --> + <access origin="http://google.com" /> + <access origin="https://google.com" /> + + <!-- Access to the subdomain maps.google.com --> + <access origin="http://maps.google.com" /> + + <!-- Access to all the subdomains on google.com --> + <access origin="http://*.google.com" /> + + <!-- Enable requests to content: URLs --> + <access origin="content:///*" /> + + <!-- Don't block any requests --> + <access origin="*" /> + +Without any `<access>` tags, only requests to `file://` URLs are allowed. However, the default Cordova application includes `<access origin="*">` by default. + +Quirk: Android also allows requests to https://ssl.gstatic.com/accessibility/javascript/android/ by default, since this is required for TalkBack to function properly. + +### Content Security Policy +Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly). + +On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g. `<video>` & WebSockets are not blocked). So, in addition to the whitelist, you should use a [Content Security Policy](http://content-security-policy.com/) `<meta>` tag on all of your pages. + +On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView). + +Here are some example CSP declarations for your `.html` pages: + + <!-- Good default declaration: + * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication + * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly + * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: + * Enable inline JS: add 'unsafe-inline' to default-src + * Enable eval(): add 'unsafe-eval' to default-src + --> + <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *"> + + <!-- Allow requests to foo.com --> + <meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com"> + + <!-- Enable all requests, inline styles, and eval() --> + <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src: 'self' 'unsafe-inline' 'unsafe-eval'"> + + <!-- Allow XHRs via https only --> + <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:"> + + <!-- Allow iframe to https://cordova.apache.org/ --> + <meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org"> diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/RELEASENOTES.md b/StoneIsland/plugins/cordova-plugin-whitelist/RELEASENOTES.md new file mode 100644 index 00000000..703552ca --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/RELEASENOTES.md @@ -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. +# +--> +# Release Notes + +### 1.0.0 (Mar 25, 2015) +* CB-8739 added missing license headers +* Add @Override to CustomConfigXmlParser methods +* Change ID to cordova-plugin-whitelist rather than reverse-DNS-style +* Tweak CSP examples in README +* CB-8660 remove extra commas from package.json diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/package.json b/StoneIsland/plugins/cordova-plugin-whitelist/package.json new file mode 100644 index 00000000..2c72e256 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/package.json @@ -0,0 +1,34 @@ +{ + "name": "cordova-plugin-whitelist", + "version": "1.0.0", + "description": "Cordova Whitelist Plugin", + "cordova": { + "platforms": [ + "android", + "ios" + ] + }, + "repository": { + "type": "git", + "url": "https://git-wip-us.apache.org/repos/asf/cordova-plugin-whitelist.git" + }, + "keywords": [ + "cordova", + "whitelist", + "ecosystem:cordova", + "cordova-android", + "cordova-ios" + ], + "engines": [ + { + "name": "cordova-android", + "version": ">=4.0.0-dev" + }, + { + "name": "cordova-ios", + "version": ">=4.0.0-dev" + } + ], + "author": "Apache Software Foundation", + "license": "Apache 2.0" +} diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/plugin.xml b/StoneIsland/plugins/cordova-plugin-whitelist/plugin.xml new file mode 100644 index 00000000..2ec60b3c --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/plugin.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" + id="cordova-plugin-whitelist" + version="1.0.0"> + <name>Whitelist</name> + <description>Cordova Network Whitelist Plugin</description> + <license>Apache 2.0</license> + <keywords>cordova,whitelist,policy</keywords> + + <engines> + <engine name="cordova-android" version=">=4.0.0-dev" /> + </engines> + + <platform name="android"> + <config-file target="res/xml/config.xml" parent="/*"> + <feature name="Whitelist" > + <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin"/> + <param name="onload" value="true" /> + </feature> + </config-file> + + <source-file src="src/android/WhitelistPlugin.java" target-dir="src/org/apache/cordova/whitelist" /> + + <js-module src="whitelist.js" name="whitelist"> + <runs /> + </js-module> + </platform> +</plugin> diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/src/android/WhitelistPlugin.java b/StoneIsland/plugins/cordova-plugin-whitelist/src/android/WhitelistPlugin.java new file mode 100644 index 00000000..4e4f57e1 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/src/android/WhitelistPlugin.java @@ -0,0 +1,161 @@ +/* + 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. +*/ + +package org.apache.cordova.whitelist; + +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.ConfigXmlParser; +import org.apache.cordova.Whitelist; +import org.xmlpull.v1.XmlPullParser; + +import android.content.Context; +import android.util.Log; + +public class WhitelistPlugin extends CordovaPlugin { + private static final String LOG_TAG = "WhitelistPlugin"; + private Whitelist allowedNavigations; + private Whitelist allowedIntents; + private Whitelist allowedRequests; + + // Used when instantiated via reflection by PluginManager + public WhitelistPlugin() { + } + // These can be used by embedders to allow Java-configuration of whitelists. + public WhitelistPlugin(Context context) { + this(new Whitelist(), new Whitelist(), null); + new CustomConfigXmlParser().parse(context); + } + public WhitelistPlugin(XmlPullParser xmlParser) { + this(new Whitelist(), new Whitelist(), null); + new CustomConfigXmlParser().parse(xmlParser); + } + public WhitelistPlugin(Whitelist allowedNavigations, Whitelist allowedIntents, Whitelist allowedRequests) { + if (allowedRequests == null) { + allowedRequests = new Whitelist(); + allowedRequests.addWhiteListEntry("file:///*", false); + allowedRequests.addWhiteListEntry("data:*", false); + } + this.allowedNavigations = allowedNavigations; + this.allowedIntents = allowedIntents; + this.allowedRequests = allowedRequests; + } + @Override + public void pluginInitialize() { + if (allowedNavigations == null) { + allowedNavigations = new Whitelist(); + allowedIntents = new Whitelist(); + allowedRequests = new Whitelist(); + new CustomConfigXmlParser().parse(webView.getContext()); + } + } + + private class CustomConfigXmlParser extends ConfigXmlParser { + @Override + public void handleStartTag(XmlPullParser xml) { + String strNode = xml.getName(); + if (strNode.equals("content")) { + String startPage = xml.getAttributeValue(null, "src"); + allowedNavigations.addWhiteListEntry(startPage, false); + } else if (strNode.equals("allow-navigation")) { + String origin = xml.getAttributeValue(null, "href"); + if ("*".equals(origin)) { + allowedNavigations.addWhiteListEntry("http://*/*", false); + allowedNavigations.addWhiteListEntry("https://*/*", false); + allowedNavigations.addWhiteListEntry("data:*", false); + } else { + allowedNavigations.addWhiteListEntry(origin, false); + } + } else if (strNode.equals("allow-intent")) { + String origin = xml.getAttributeValue(null, "href"); + allowedIntents.addWhiteListEntry(origin, false); + } else if (strNode.equals("access")) { + String origin = xml.getAttributeValue(null, "origin"); + String subdomains = xml.getAttributeValue(null, "subdomains"); + boolean external = (xml.getAttributeValue(null, "launch-external") != null); + if (origin != null) { + if (external) { + Log.w(LOG_TAG, "Found <access launch-external> within config.xml. Please use <allow-intent> instead."); + allowedIntents.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); + } else { + if ("*".equals(origin)) { + allowedRequests.addWhiteListEntry("http://*/*", false); + allowedRequests.addWhiteListEntry("https://*/*", false); + } else { + allowedRequests.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); + } + } + } + } + } + @Override + public void handleEndTag(XmlPullParser xml) { + } + } + + @Override + public Boolean shouldAllowNavigation(String url) { + if (allowedNavigations.isUrlWhiteListed(url)) { + return true; + } + return null; // Default policy + } + + @Override + public Boolean shouldAllowRequest(String url) { + if (Boolean.TRUE == shouldAllowNavigation(url)) { + return true; + } + if (allowedRequests.isUrlWhiteListed(url)) { + return true; + } + return null; // Default policy + } + + @Override + public Boolean shouldOpenExternalUrl(String url) { + if (allowedIntents.isUrlWhiteListed(url)) { + return true; + } + return null; // Default policy + } + + public Whitelist getAllowedNavigations() { + return allowedNavigations; + } + + public void setAllowedNavigations(Whitelist allowedNavigations) { + this.allowedNavigations = allowedNavigations; + } + + public Whitelist getAllowedIntents() { + return allowedIntents; + } + + public void setAllowedIntents(Whitelist allowedIntents) { + this.allowedIntents = allowedIntents; + } + + public Whitelist getAllowedRequests() { + return allowedRequests; + } + + public void setAllowedRequests(Whitelist allowedRequests) { + this.allowedRequests = allowedRequests; + } +} diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/src/ios/CDVNavigationWhitelistPlugin.h b/StoneIsland/plugins/cordova-plugin-whitelist/src/ios/CDVNavigationWhitelistPlugin.h new file mode 100644 index 00000000..d0b93654 --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/src/ios/CDVNavigationWhitelistPlugin.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. + */ + +#import <UIKit/UIKit.h> +#import <Cordova/CDVPlugin.h> +#import <Cordova/CDVWhitelist.h> + +@interface CDVNavigationWhitelistPlugin : CDVPlugin {} + +@property (nonatomic, readonly, strong) CDVWhitelist* whitelist; // readonly for public + +- (BOOL)shouldAllowNavigationToURL:(NSURL *)url; +- (BOOL)shouldAllowRequestForURL:(NSURL *)url; + +@end diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/src/ios/CDVNavigationWhitelistPlugin.m b/StoneIsland/plugins/cordova-plugin-whitelist/src/ios/CDVNavigationWhitelistPlugin.m new file mode 100644 index 00000000..5895e89b --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/src/ios/CDVNavigationWhitelistPlugin.m @@ -0,0 +1,89 @@ +/* + 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 "CDVNavigationWhitelistPlugin.h" +#import <Cordova/CDVViewController.h> + +#pragma mark CDVNavigationWhitelistConfigParser + +@interface CDVNavigationWhitelistConfigParser : NSObject <NSXMLParserDelegate> {} + +@property (nonatomic, strong) NSMutableArray* whitelistHosts; + +@end + +@implementation CDVNavigationWhitelistConfigParser + +@synthesize whitelistHosts; + +- (id)init +{ + self = [super init]; + if (self != nil) { + self.whitelistHosts = [[NSMutableArray alloc] initWithCapacity:30]; + [self.whitelistHosts addObject:@"file:///*"]; + [self.whitelistHosts addObject:@"content:///*"]; + [self.whitelistHosts addObject:@"data:///*"]; + } + return self; +} + +- (void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict +{ + if ([elementName isEqualToString:@"allow-navigation"]) { + [whitelistHosts addObject:attributeDict[@"href"]]; + } +} + +- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName +{ +} + +- (void)parser:(NSXMLParser*)parser parseErrorOccurred:(NSError*)parseError +{ + NSAssert(NO, @"config.xml parse error line %ld col %ld", (long)[parser lineNumber], (long)[parser columnNumber]); +} + + +@end + +#pragma mark CDVNavigationWhitelistPlugin + +@interface CDVNavigationWhitelistPlugin () {} +@property (nonatomic, strong) CDVWhitelist* whitelist; +@end + +@implementation CDVNavigationWhitelistPlugin + +@synthesize whitelist; + +- (void)setViewController:(UIViewController *)viewController +{ + if ([viewController isKindOfClass:[CDVViewController class]]) { + CDVWhitelistConfigParser *whitelistConfigParser = [[CDVWhitelistConfigParser alloc] init]; + [(CDVViewController *)viewController parseSettingsWithParser:whitelistConfigParser]; + self.whitelist = [[CDVWhitelist alloc] initWithArray:whitelistConfigParser.whitelistHosts]; + } +} + +- (BOOL)shouldAllowNavigationToURL:(NSURL *)url +{ + return [self.whitelist URLIsAllowed:url]; +} +@end diff --git a/StoneIsland/plugins/cordova-plugin-whitelist/whitelist.js b/StoneIsland/plugins/cordova-plugin-whitelist/whitelist.js new file mode 100644 index 00000000..74d7a99d --- /dev/null +++ b/StoneIsland/plugins/cordova-plugin-whitelist/whitelist.js @@ -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. + * +*/ + +if (!document.querySelector('meta[http-equiv=Content-Security-Policy]')) { + var msg = 'No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.'; + console.error(msg); + setInterval(function() { + console.warn(msg); + }, 10000); +} diff --git a/StoneIsland/plugins/fetch.json b/StoneIsland/plugins/fetch.json new file mode 100644 index 00000000..7364381e --- /dev/null +++ b/StoneIsland/plugins/fetch.json @@ -0,0 +1,66 @@ +{ + "cordova-plugin-geolocation": { + "source": { + "type": "registry", + "id": "cordova-plugin-geolocation" + }, + "is_top_level": true, + "variables": {} + }, + "cordova-plugin-splashscreen": { + "source": { + "type": "registry", + "id": "cordova-plugin-splashscreen" + }, + "is_top_level": true, + "variables": {} + }, + "cordova-plugin-dialogs": { + "source": { + "type": "registry", + "id": "cordova-plugin-dialogs" + }, + "is_top_level": true, + "variables": {} + }, + "cordova-plugin-network-information": { + "source": { + "type": "registry", + "id": "cordova-plugin-network-information" + }, + "is_top_level": true, + "variables": {} + }, + "cordova-plugin-device": { + "source": { + "type": "registry", + "id": "cordova-plugin-device" + }, + "is_top_level": true, + "variables": {} + }, + "cordova-plugin-console": { + "source": { + "type": "registry", + "id": "cordova-plugin-console" + }, + "is_top_level": true, + "variables": {} + }, + "com.ionic.keyboard": { + "source": { + "type": "registry", + "id": "com.ionic.keyboard" + }, + "is_top_level": true, + "variables": {} + }, + "cordova-plugin-whitelist": { + "source": { + "type": "registry", + "id": "cordova-plugin-whitelist@1" + }, + "is_top_level": true, + "variables": {} + } +}
\ No newline at end of file diff --git a/StoneIsland/plugins/ios.json b/StoneIsland/plugins/ios.json new file mode 100644 index 00000000..567e19fb --- /dev/null +++ b/StoneIsland/plugins/ios.json @@ -0,0 +1,109 @@ +{ + "prepare_queue": { + "installed": [], + "uninstalled": [] + }, + "config_munge": { + "files": { + "config.xml": { + "parents": { + "/*": [ + { + "xml": "<feature name=\"Keyboard\"><param name=\"ios-package\" onload=\"true\" value=\"IonicKeyboard\" /></feature>", + "count": 1 + }, + { + "xml": "<feature name=\"Console\"><param name=\"ios-package\" value=\"CDVLogger\" /></feature>", + "count": 1 + }, + { + "xml": "<feature name=\"Device\"><param name=\"ios-package\" value=\"CDVDevice\" /></feature>", + "count": 1 + }, + { + "xml": "<feature name=\"Notification\"><param name=\"ios-package\" value=\"CDVNotification\" /></feature>", + "count": 1 + }, + { + "xml": "<feature name=\"Geolocation\"><param name=\"ios-package\" value=\"CDVLocation\" /></feature>", + "count": 1 + }, + { + "xml": "<feature name=\"NetworkStatus\"><param name=\"ios-package\" value=\"CDVConnection\" /></feature>", + "count": 1 + }, + { + "xml": "<feature name=\"SplashScreen\"><param name=\"ios-package\" value=\"CDVSplashScreen\" /><param name=\"onload\" value=\"true\" /></feature>", + "count": 1 + } + ] + } + }, + "framework": { + "parents": { + "AudioToolbox.framework": [ + { + "xml": true, + "count": 1 + } + ], + "CoreLocation.framework": [ + { + "xml": false, + "count": 1 + } + ], + "SystemConfiguration.framework": [ + { + "xml": true, + "count": 1 + } + ], + "CoreGraphics.framework": [ + { + "xml": false, + "count": 1 + } + ] + } + }, + "*-Info.plist": { + "parents": { + "NSLocationWhenInUseUsageDescription": [ + { + "xml": "<string />", + "count": 1 + } + ] + } + } + } + }, + "installed_plugins": { + "cordova-plugin-whitelist": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "com.ionic.keyboard": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "cordova-plugin-console": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "cordova-plugin-device": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "cordova-plugin-dialogs": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "cordova-plugin-geolocation": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "cordova-plugin-network-information": { + "PACKAGE_NAME": "io.cordova.hellocordova" + }, + "cordova-plugin-splashscreen": { + "PACKAGE_NAME": "io.cordova.hellocordova" + } + }, + "dependent_plugins": {} +}
\ No newline at end of file diff --git a/StoneIsland/www/css/index.css b/StoneIsland/www/css/index.css new file mode 100644 index 00000000..a0b5f2b1 --- /dev/null +++ b/StoneIsland/www/css/index.css @@ -0,0 +1,15 @@ +* { + -webkit-tap-highlight-color: rgba(0,0,0,0); +} +body, html { + height:100%; width:100%; margin:0px; padding:0px; +} +body { + -webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */ + -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */ + -webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */ + background: white; + font-family: 'HelveticaNeue-Light', 'HelveticaNeue', sans-serif; + font-size: 12px; +} + diff --git a/StoneIsland/www/index.html b/StoneIsland/www/index.html new file mode 100644 index 00000000..6deac067 --- /dev/null +++ b/StoneIsland/www/index.html @@ -0,0 +1,33 @@ +<!doctype html> +<html> +<head> + <!-- + Customize this policy to fit your own app's needs. For more guidance, see: + https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy + Some notes: + * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication + * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly + * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: + * Enable inline JS: add 'unsafe-inline' to default-src + --> +<!-- + <meta http-equiv="Content-Security-Policy" content="default-src 'self' lvh.me lvh.me:5000 data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"> +--> + <meta name="format-detection" content="telephone=no"> + <meta name="msapplication-tap-highlight" content="no"> + <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> + <link rel="stylesheet" type="text/css" href="css/index.css"> + <title>Stone Island</title> +</head> +<body> +</body> +<script src="cordova.js"></script> +<script src="js/vendor/jquery-2.1.4.min.js"></script> +<script src="js/vendor/lodash.min.js"></script> +<script src="js/vendor/oktween.js"></script> +<script src="js/vendor/util.js"></script> +<script src="js/vendor/view/view.js"></script> +<script src="js/vendor/view/formview.js"></script> +<script src="js/vendor/view/router.js"></script> +<script src="js/index.js"></script> +</html> diff --git a/StoneIsland/www/js/index.js b/StoneIsland/www/js/index.js new file mode 100644 index 00000000..676dedfc --- /dev/null +++ b/StoneIsland/www/js/index.js @@ -0,0 +1,19 @@ +var app = (function(){ + var app = {} + + app.init = function(){ + app.bind() + } + + app.bind = function(){ + document.addEventListener('deviceready', app.ready, false) + } + + app.ready = function(){ + app.view = null + app.router = new SiteRouter () + } + + app.init() + +})() diff --git a/StoneIsland/www/js/lib/router.js b/StoneIsland/www/js/lib/router.js new file mode 100644 index 00000000..b1c33cb7 --- /dev/null +++ b/StoneIsland/www/js/lib/router.js @@ -0,0 +1,9 @@ +var SiteRouter = Router.extend({ + + el: "body", + + routes: { + "/": 'login', + } + +})
\ No newline at end of file diff --git a/StoneIsland/www/js/vendor/jquery-2.1.4.min.js b/StoneIsland/www/js/vendor/jquery-2.1.4.min.js new file mode 100644 index 00000000..49990d6e --- /dev/null +++ b/StoneIsland/www/js/vendor/jquery-2.1.4.min.js @@ -0,0 +1,4 @@ +/*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){ +return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function ya(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),f.removeChild(c),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",ta(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xa(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fa(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ba.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wa(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Ja(this,!0)},hide:function(){return Ja(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Ka.propHooks.scrollTop=Ka.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||ta(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Na.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ta(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ua(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wa(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:La||Sa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xa,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xa(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pa.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Ya,Za,$a=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Za:Ya)), +void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cb=n.now(),db=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function rb(a,b,c,d){var e={},f=a===mb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function sb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function tb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function ub(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=gb.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+nb+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=rb(mb,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=tb(k,v,f)),u=ub(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Cb[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Fb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Jb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Jb(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n}); diff --git a/StoneIsland/www/js/vendor/lodash.min.js b/StoneIsland/www/js/vendor/lodash.min.js new file mode 100644 index 00000000..e6c9820b --- /dev/null +++ b/StoneIsland/www/js/vendor/lodash.min.js @@ -0,0 +1,98 @@ +/** + * @license + * lodash 3.10.1 (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE + * Build: `lodash modern -o ./lodash.js` + */ +;(function(){function n(n,t){if(n!==t){var r=null===n,e=n===w,u=n===n,o=null===t,i=t===w,f=t===t;if(n>t&&!o||!u||r&&!i&&f||e&&f)return 1;if(n<t&&!r||!f||o&&!e&&u||i&&u)return-1}return 0}function t(n,t,r){for(var e=n.length,u=r?e:-1;r?u--:++u<e;)if(t(n[u],u,n))return u;return-1}function r(n,t,r){if(t!==t)return p(n,r);r-=1;for(var e=n.length;++r<e;)if(n[r]===t)return r;return-1}function e(n){return typeof n=="function"||false}function u(n){return null==n?"":n+""}function o(n,t){for(var r=-1,e=n.length;++r<e&&-1<t.indexOf(n.charAt(r));); +return r}function i(n,t){for(var r=n.length;r--&&-1<t.indexOf(n.charAt(r)););return r}function f(t,r){return n(t.a,r.a)||t.b-r.b}function a(n){return Nn[n]}function c(n){return Tn[n]}function l(n,t,r){return t?n=Bn[n]:r&&(n=Dn[n]),"\\"+n}function s(n){return"\\"+Dn[n]}function p(n,t,r){var e=n.length;for(t+=r?0:-1;r?t--:++t<e;){var u=n[t];if(u!==u)return t}return-1}function h(n){return!!n&&typeof n=="object"}function _(n){return 160>=n&&9<=n&&13>=n||32==n||160==n||5760==n||6158==n||8192<=n&&(8202>=n||8232==n||8233==n||8239==n||8287==n||12288==n||65279==n); +}function v(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;)n[r]===t&&(n[r]=z,o[++u]=r);return o}function g(n){for(var t=-1,r=n.length;++t<r&&_(n.charCodeAt(t)););return t}function y(n){for(var t=n.length;t--&&_(n.charCodeAt(t)););return t}function d(n){return Ln[n]}function m(_){function Nn(n){if(h(n)&&!(Oo(n)||n instanceof zn)){if(n instanceof Ln)return n;if(nu.call(n,"__chain__")&&nu.call(n,"__wrapped__"))return Mr(n)}return new Ln(n)}function Tn(){}function Ln(n,t,r){this.__wrapped__=n,this.__actions__=r||[], +this.__chain__=!!t}function zn(n){this.__wrapped__=n,this.__actions__=[],this.__dir__=1,this.__filtered__=false,this.__iteratees__=[],this.__takeCount__=Ru,this.__views__=[]}function Bn(){this.__data__={}}function Dn(n){var t=n?n.length:0;for(this.data={hash:gu(null),set:new lu};t--;)this.push(n[t])}function Mn(n,t){var r=n.data;return(typeof t=="string"||ge(t)?r.set.has(t):r.hash[t])?0:-1}function qn(n,t){var r=-1,e=n.length;for(t||(t=Be(e));++r<e;)t[r]=n[r];return t}function Pn(n,t){for(var r=-1,e=n.length;++r<e&&false!==t(n[r],r,n);); +return n}function Kn(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return false;return true}function Vn(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;){var i=n[r];t(i,r,n)&&(o[++u]=i)}return o}function Gn(n,t){for(var r=-1,e=n.length,u=Be(e);++r<e;)u[r]=t(n[r],r,n);return u}function Jn(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function Xn(n,t,r,e){var u=-1,o=n.length;for(e&&o&&(r=n[++u]);++u<o;)r=t(r,n[u],u,n);return r}function Hn(n,t){for(var r=-1,e=n.length;++r<e;)if(t(n[r],r,n))return true; +return false}function Qn(n,t,r,e){return n!==w&&nu.call(e,r)?n:t}function nt(n,t,r){for(var e=-1,u=zo(t),o=u.length;++e<o;){var i=u[e],f=n[i],a=r(f,t[i],i,n,t);(a===a?a===f:f!==f)&&(f!==w||i in n)||(n[i]=a)}return n}function tt(n,t){return null==t?n:et(t,zo(t),n)}function rt(n,t){for(var r=-1,e=null==n,u=!e&&Er(n),o=u?n.length:0,i=t.length,f=Be(i);++r<i;){var a=t[r];f[r]=u?Cr(a,o)?n[a]:w:e?w:n[a]}return f}function et(n,t,r){r||(r={});for(var e=-1,u=t.length;++e<u;){var o=t[e];r[o]=n[o]}return r}function ut(n,t,r){ +var e=typeof n;return"function"==e?t===w?n:Bt(n,t,r):null==n?Fe:"object"==e?bt(n):t===w?ze(n):xt(n,t)}function ot(n,t,r,e,u,o,i){var f;if(r&&(f=u?r(n,e,u):r(n)),f!==w)return f;if(!ge(n))return n;if(e=Oo(n)){if(f=kr(n),!t)return qn(n,f)}else{var a=ru.call(n),c=a==K;if(a!=Z&&a!=B&&(!c||u))return Fn[a]?Rr(n,a,t):u?n:{};if(f=Ir(c?{}:n),!t)return tt(f,n)}for(o||(o=[]),i||(i=[]),u=o.length;u--;)if(o[u]==n)return i[u];return o.push(n),i.push(f),(e?Pn:_t)(n,function(e,u){f[u]=ot(e,t,r,u,n,o,i)}),f}function it(n,t,r){ +if(typeof n!="function")throw new Ge(L);return su(function(){n.apply(w,r)},t)}function ft(n,t){var e=n?n.length:0,u=[];if(!e)return u;var o=-1,i=xr(),f=i===r,a=f&&t.length>=F&&gu&&lu?new Dn(t):null,c=t.length;a&&(i=Mn,f=false,t=a);n:for(;++o<e;)if(a=n[o],f&&a===a){for(var l=c;l--;)if(t[l]===a)continue n;u.push(a)}else 0>i(t,a,0)&&u.push(a);return u}function at(n,t){var r=true;return Su(n,function(n,e,u){return r=!!t(n,e,u)}),r}function ct(n,t,r,e){var u=e,o=u;return Su(n,function(n,i,f){i=+t(n,i,f),(r(i,u)||i===e&&i===o)&&(u=i, +o=n)}),o}function lt(n,t){var r=[];return Su(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function st(n,t,r,e){var u;return r(n,function(n,r,o){return t(n,r,o)?(u=e?r:n,false):void 0}),u}function pt(n,t,r,e){e||(e=[]);for(var u=-1,o=n.length;++u<o;){var i=n[u];h(i)&&Er(i)&&(r||Oo(i)||pe(i))?t?pt(i,t,r,e):Jn(e,i):r||(e[e.length]=i)}return e}function ht(n,t){Nu(n,t,Re)}function _t(n,t){return Nu(n,t,zo)}function vt(n,t){return Tu(n,t,zo)}function gt(n,t){for(var r=-1,e=t.length,u=-1,o=[];++r<e;){var i=t[r]; +ve(n[i])&&(o[++u]=i)}return o}function yt(n,t,r){if(null!=n){r!==w&&r in Br(n)&&(t=[r]),r=0;for(var e=t.length;null!=n&&r<e;)n=n[t[r++]];return r&&r==e?n:w}}function dt(n,t,r,e,u,o){if(n===t)n=true;else if(null==n||null==t||!ge(n)&&!h(t))n=n!==n&&t!==t;else n:{var i=dt,f=Oo(n),a=Oo(t),c=D,l=D;f||(c=ru.call(n),c==B?c=Z:c!=Z&&(f=xe(n))),a||(l=ru.call(t),l==B?l=Z:l!=Z&&xe(t));var s=c==Z,a=l==Z,l=c==l;if(!l||f||s){if(!e&&(c=s&&nu.call(n,"__wrapped__"),a=a&&nu.call(t,"__wrapped__"),c||a)){n=i(c?n.value():n,a?t.value():t,r,e,u,o); +break n}if(l){for(u||(u=[]),o||(o=[]),c=u.length;c--;)if(u[c]==n){n=o[c]==t;break n}u.push(n),o.push(t),n=(f?yr:mr)(n,t,i,r,e,u,o),u.pop(),o.pop()}else n=false}else n=dr(n,t,c)}return n}function mt(n,t,r){var e=t.length,u=e,o=!r;if(null==n)return!u;for(n=Br(n);e--;){var i=t[e];if(o&&i[2]?i[1]!==n[i[0]]:!(i[0]in n))return false}for(;++e<u;){var i=t[e],f=i[0],a=n[f],c=i[1];if(o&&i[2]){if(a===w&&!(f in n))return false}else if(i=r?r(a,c,f):w,i===w?!dt(c,a,r,true):!i)return false}return true}function wt(n,t){var r=-1,e=Er(n)?Be(n.length):[]; +return Su(n,function(n,u,o){e[++r]=t(n,u,o)}),e}function bt(n){var t=Ar(n);if(1==t.length&&t[0][2]){var r=t[0][0],e=t[0][1];return function(n){return null==n?false:n[r]===e&&(e!==w||r in Br(n))}}return function(n){return mt(n,t)}}function xt(n,t){var r=Oo(n),e=Wr(n)&&t===t&&!ge(t),u=n+"";return n=Dr(n),function(o){if(null==o)return false;var i=u;if(o=Br(o),!(!r&&e||i in o)){if(o=1==n.length?o:yt(o,Et(n,0,-1)),null==o)return false;i=Zr(n),o=Br(o)}return o[i]===t?t!==w||i in o:dt(t,o[i],w,true)}}function At(n,t,r,e,u){ +if(!ge(n))return n;var o=Er(t)&&(Oo(t)||xe(t)),i=o?w:zo(t);return Pn(i||t,function(f,a){if(i&&(a=f,f=t[a]),h(f)){e||(e=[]),u||(u=[]);n:{for(var c=a,l=e,s=u,p=l.length,_=t[c];p--;)if(l[p]==_){n[c]=s[p];break n}var p=n[c],v=r?r(p,_,c,n,t):w,g=v===w;g&&(v=_,Er(_)&&(Oo(_)||xe(_))?v=Oo(p)?p:Er(p)?qn(p):[]:me(_)||pe(_)?v=pe(p)?ke(p):me(p)?p:{}:g=false),l.push(_),s.push(v),g?n[c]=At(v,_,r,l,s):(v===v?v!==p:p===p)&&(n[c]=v)}}else c=n[a],l=r?r(c,f,a,n,t):w,(s=l===w)&&(l=f),l===w&&(!o||a in n)||!s&&(l===l?l===c:c!==c)||(n[a]=l); +}),n}function jt(n){return function(t){return null==t?w:t[n]}}function kt(n){var t=n+"";return n=Dr(n),function(r){return yt(r,n,t)}}function It(n,t){for(var r=n?t.length:0;r--;){var e=t[r];if(e!=u&&Cr(e)){var u=e;pu.call(n,e,1)}}}function Rt(n,t){return n+yu(ku()*(t-n+1))}function Ot(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function Et(n,t,r){var e=-1,u=n.length;for(t=null==t?0:+t||0,0>t&&(t=-t>u?0:u+t),r=r===w||r>u?u:+r||0,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=Be(u);++e<u;)r[e]=n[e+t]; +return r}function Ct(n,t){var r;return Su(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function Ut(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].c;return n}function Wt(t,r,e){var u=wr(),o=-1;return r=Gn(r,function(n){return u(n)}),t=wt(t,function(n){return{a:Gn(r,function(t){return t(n)}),b:++o,c:n}}),Ut(t,function(t,r){var u;n:{for(var o=-1,i=t.a,f=r.a,a=i.length,c=e.length;++o<a;)if(u=n(i[o],f[o])){if(o>=c)break n;o=e[o],u*="asc"===o||true===o?1:-1;break n}u=t.b-r.b}return u})}function $t(n,t){ +var r=0;return Su(n,function(n,e,u){r+=+t(n,e,u)||0}),r}function St(n,t){var e=-1,u=xr(),o=n.length,i=u===r,f=i&&o>=F,a=f&&gu&&lu?new Dn(void 0):null,c=[];a?(u=Mn,i=false):(f=false,a=t?[]:c);n:for(;++e<o;){var l=n[e],s=t?t(l,e,n):l;if(i&&l===l){for(var p=a.length;p--;)if(a[p]===s)continue n;t&&a.push(s),c.push(l)}else 0>u(a,s,0)&&((t||f)&&a.push(s),c.push(l))}return c}function Ft(n,t){for(var r=-1,e=t.length,u=Be(e);++r<e;)u[r]=n[t[r]];return u}function Nt(n,t,r,e){for(var u=n.length,o=e?u:-1;(e?o--:++o<u)&&t(n[o],o,n);); +return r?Et(n,e?0:o,e?o+1:u):Et(n,e?o+1:0,e?u:o)}function Tt(n,t){var r=n;r instanceof zn&&(r=r.value());for(var e=-1,u=t.length;++e<u;)var o=t[e],r=o.func.apply(o.thisArg,Jn([r],o.args));return r}function Lt(n,t,r){var e=0,u=n?n.length:e;if(typeof t=="number"&&t===t&&u<=Eu){for(;e<u;){var o=e+u>>>1,i=n[o];(r?i<=t:i<t)&&null!==i?e=o+1:u=o}return u}return zt(n,t,Fe,r)}function zt(n,t,r,e){t=r(t);for(var u=0,o=n?n.length:0,i=t!==t,f=null===t,a=t===w;u<o;){var c=yu((u+o)/2),l=r(n[c]),s=l!==w,p=l===l; +(i?p||e:f?p&&s&&(e||null!=l):a?p&&(e||s):null==l?0:e?l<=t:l<t)?u=c+1:o=c}return xu(o,Ou)}function Bt(n,t,r){if(typeof n!="function")return Fe;if(t===w)return n;switch(r){case 1:return function(r){return n.call(t,r)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,o){return n.call(t,r,e,u,o)};case 5:return function(r,e,u,o,i){return n.call(t,r,e,u,o,i)}}return function(){return n.apply(t,arguments)}}function Dt(n){var t=new ou(n.byteLength);return new hu(t).set(new hu(n)), +t}function Mt(n,t,r){for(var e=r.length,u=-1,o=bu(n.length-e,0),i=-1,f=t.length,a=Be(f+o);++i<f;)a[i]=t[i];for(;++u<e;)a[r[u]]=n[u];for(;o--;)a[i++]=n[u++];return a}function qt(n,t,r){for(var e=-1,u=r.length,o=-1,i=bu(n.length-u,0),f=-1,a=t.length,c=Be(i+a);++o<i;)c[o]=n[o];for(i=o;++f<a;)c[i+f]=t[f];for(;++e<u;)c[i+r[e]]=n[o++];return c}function Pt(n,t){return function(r,e,u){var o=t?t():{};if(e=wr(e,u,3),Oo(r)){u=-1;for(var i=r.length;++u<i;){var f=r[u];n(o,f,e(f,u,r),r)}}else Su(r,function(t,r,u){ +n(o,t,e(t,r,u),u)});return o}}function Kt(n){return le(function(t,r){var e=-1,u=null==t?0:r.length,o=2<u?r[u-2]:w,i=2<u?r[2]:w,f=1<u?r[u-1]:w;for(typeof o=="function"?(o=Bt(o,f,5),u-=2):(o=typeof f=="function"?f:w,u-=o?1:0),i&&Ur(r[0],r[1],i)&&(o=3>u?w:o,u=1);++e<u;)(i=r[e])&&n(t,i,o);return t})}function Vt(n,t){return function(r,e){var u=r?Bu(r):0;if(!Sr(u))return n(r,e);for(var o=t?u:-1,i=Br(r);(t?o--:++o<u)&&false!==e(i[o],o,i););return r}}function Zt(n){return function(t,r,e){var u=Br(t);e=e(t);for(var o=e.length,i=n?o:-1;n?i--:++i<o;){ +var f=e[i];if(false===r(u[f],f,u))break}return t}}function Yt(n,t){function r(){return(this&&this!==Zn&&this instanceof r?e:n).apply(t,arguments)}var e=Jt(n);return r}function Gt(n){return function(t){var r=-1;t=$e(Ce(t));for(var e=t.length,u="";++r<e;)u=n(u,t[r],r);return u}}function Jt(n){return function(){var t=arguments;switch(t.length){case 0:return new n;case 1:return new n(t[0]);case 2:return new n(t[0],t[1]);case 3:return new n(t[0],t[1],t[2]);case 4:return new n(t[0],t[1],t[2],t[3]);case 5: +return new n(t[0],t[1],t[2],t[3],t[4]);case 6:return new n(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new n(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=$u(n.prototype),t=n.apply(r,t);return ge(t)?t:r}}function Xt(n){function t(r,e,u){return u&&Ur(r,e,u)&&(e=w),r=gr(r,n,w,w,w,w,w,e),r.placeholder=t.placeholder,r}return t}function Ht(n,t){return le(function(r){var e=r[0];return null==e?e:(r.push(t),n.apply(w,r))})}function Qt(n,t){return function(r,e,u){if(u&&Ur(r,e,u)&&(e=w),e=wr(e,u,3),1==e.length){ +u=r=Oo(r)?r:zr(r);for(var o=e,i=-1,f=u.length,a=t,c=a;++i<f;){var l=u[i],s=+o(l);n(s,a)&&(a=s,c=l)}if(u=c,!r.length||u!==t)return u}return ct(r,e,n,t)}}function nr(n,r){return function(e,u,o){return u=wr(u,o,3),Oo(e)?(u=t(e,u,r),-1<u?e[u]:w):st(e,u,n)}}function tr(n){return function(r,e,u){return r&&r.length?(e=wr(e,u,3),t(r,e,n)):-1}}function rr(n){return function(t,r,e){return r=wr(r,e,3),st(t,r,n,true)}}function er(n){return function(){for(var t,r=arguments.length,e=n?r:-1,u=0,o=Be(r);n?e--:++e<r;){ +var i=o[u++]=arguments[e];if(typeof i!="function")throw new Ge(L);!t&&Ln.prototype.thru&&"wrapper"==br(i)&&(t=new Ln([],true))}for(e=t?-1:r;++e<r;){var i=o[e],u=br(i),f="wrapper"==u?zu(i):w;t=f&&$r(f[0])&&f[1]==(E|k|R|C)&&!f[4].length&&1==f[9]?t[br(f[0])].apply(t,f[3]):1==i.length&&$r(i)?t[u]():t.thru(i)}return function(){var n=arguments,e=n[0];if(t&&1==n.length&&Oo(e)&&e.length>=F)return t.plant(e).value();for(var u=0,n=r?o[u].apply(this,n):e;++u<r;)n=o[u].call(this,n);return n}}}function ur(n,t){ +return function(r,e,u){return typeof e=="function"&&u===w&&Oo(r)?n(r,e):t(r,Bt(e,u,3))}}function or(n){return function(t,r,e){return(typeof r!="function"||e!==w)&&(r=Bt(r,e,3)),n(t,r,Re)}}function ir(n){return function(t,r,e){return(typeof r!="function"||e!==w)&&(r=Bt(r,e,3)),n(t,r)}}function fr(n){return function(t,r,e){var u={};return r=wr(r,e,3),_t(t,function(t,e,o){o=r(t,e,o),e=n?o:e,t=n?t:o,u[e]=t}),u}}function ar(n){return function(t,r,e){return t=u(t),(n?t:"")+pr(t,r,e)+(n?"":t)}}function cr(n){ +var t=le(function(r,e){var u=v(e,t.placeholder);return gr(r,n,w,e,u)});return t}function lr(n,t){return function(r,e,u,o){var i=3>arguments.length;return typeof e=="function"&&o===w&&Oo(r)?n(r,e,u,i):Ot(r,wr(e,o,4),u,i,t)}}function sr(n,t,r,e,u,o,i,f,a,c){function l(){for(var m=arguments.length,b=m,j=Be(m);b--;)j[b]=arguments[b];if(e&&(j=Mt(j,e,u)),o&&(j=qt(j,o,i)),_||y){var b=l.placeholder,k=v(j,b),m=m-k.length;if(m<c){var I=f?qn(f):w,m=bu(c-m,0),E=_?k:w,k=_?w:k,C=_?j:w,j=_?w:j;return t|=_?R:O,t&=~(_?O:R), +g||(t&=~(x|A)),j=[n,t,r,C,E,j,k,I,a,m],I=sr.apply(w,j),$r(n)&&Du(I,j),I.placeholder=b,I}}if(b=p?r:this,I=h?b[n]:n,f)for(m=j.length,E=xu(f.length,m),k=qn(j);E--;)C=f[E],j[E]=Cr(C,m)?k[C]:w;return s&&a<j.length&&(j.length=a),this&&this!==Zn&&this instanceof l&&(I=d||Jt(n)),I.apply(b,j)}var s=t&E,p=t&x,h=t&A,_=t&k,g=t&j,y=t&I,d=h?w:Jt(n);return l}function pr(n,t,r){return n=n.length,t=+t,n<t&&mu(t)?(t-=n,r=null==r?" ":r+"",Ue(r,vu(t/r.length)).slice(0,t)):""}function hr(n,t,r,e){function u(){for(var t=-1,f=arguments.length,a=-1,c=e.length,l=Be(c+f);++a<c;)l[a]=e[a]; +for(;f--;)l[a++]=arguments[++t];return(this&&this!==Zn&&this instanceof u?i:n).apply(o?r:this,l)}var o=t&x,i=Jt(n);return u}function _r(n){var t=Pe[n];return function(n,r){return(r=r===w?0:+r||0)?(r=au(10,r),t(n*r)/r):t(n)}}function vr(n){return function(t,r,e,u){var o=wr(e);return null==e&&o===ut?Lt(t,r,n):zt(t,r,o(e,u,1),n)}}function gr(n,t,r,e,u,o,i,f){var a=t&A;if(!a&&typeof n!="function")throw new Ge(L);var c=e?e.length:0;if(c||(t&=~(R|O),e=u=w),c-=u?u.length:0,t&O){var l=e,s=u;e=u=w}var p=a?w:zu(n); +return r=[n,t,r,e,u,l,s,o,i,f],p&&(e=r[1],t=p[1],f=e|t,u=t==E&&e==k||t==E&&e==C&&r[7].length<=p[8]||t==(E|C)&&e==k,(f<E||u)&&(t&x&&(r[2]=p[2],f|=e&x?0:j),(e=p[3])&&(u=r[3],r[3]=u?Mt(u,e,p[4]):qn(e),r[4]=u?v(r[3],z):qn(p[4])),(e=p[5])&&(u=r[5],r[5]=u?qt(u,e,p[6]):qn(e),r[6]=u?v(r[5],z):qn(p[6])),(e=p[7])&&(r[7]=qn(e)),t&E&&(r[8]=null==r[8]?p[8]:xu(r[8],p[8])),null==r[9]&&(r[9]=p[9]),r[0]=p[0],r[1]=f),t=r[1],f=r[9]),r[9]=null==f?a?0:n.length:bu(f-c,0)||0,(p?Lu:Du)(t==x?Yt(r[0],r[2]):t!=R&&t!=(x|R)||r[4].length?sr.apply(w,r):hr.apply(w,r),r); +}function yr(n,t,r,e,u,o,i){var f=-1,a=n.length,c=t.length;if(a!=c&&(!u||c<=a))return false;for(;++f<a;){var l=n[f],c=t[f],s=e?e(u?c:l,u?l:c,f):w;if(s!==w){if(s)continue;return false}if(u){if(!Hn(t,function(n){return l===n||r(l,n,e,u,o,i)}))return false}else if(l!==c&&!r(l,c,e,u,o,i))return false}return true}function dr(n,t,r){switch(r){case M:case q:return+n==+t;case P:return n.name==t.name&&n.message==t.message;case V:return n!=+n?t!=+t:n==+t;case Y:case G:return n==t+""}return false}function mr(n,t,r,e,u,o,i){var f=zo(n),a=f.length,c=zo(t).length; +if(a!=c&&!u)return false;for(c=a;c--;){var l=f[c];if(!(u?l in t:nu.call(t,l)))return false}for(var s=u;++c<a;){var l=f[c],p=n[l],h=t[l],_=e?e(u?h:p,u?p:h,l):w;if(_===w?!r(p,h,e,u,o,i):!_)return false;s||(s="constructor"==l)}return s||(r=n.constructor,e=t.constructor,!(r!=e&&"constructor"in n&&"constructor"in t)||typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)?true:false}function wr(n,t,r){var e=Nn.callback||Se,e=e===Se?ut:e;return r?e(n,t,r):e}function br(n){for(var t=n.name+"",r=Wu[t],e=r?r.length:0;e--;){ +var u=r[e],o=u.func;if(null==o||o==n)return u.name}return t}function xr(n,t,e){var u=Nn.indexOf||Vr,u=u===Vr?r:u;return n?u(n,t,e):u}function Ar(n){n=Oe(n);for(var t=n.length;t--;){var r=n[t][1];n[t][2]=r===r&&!ge(r)}return n}function jr(n,t){var r=null==n?w:n[t];return ye(r)?r:w}function kr(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&nu.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function Ir(n){return n=n.constructor,typeof n=="function"&&n instanceof n||(n=Ve), +new n}function Rr(n,t,r){var e=n.constructor;switch(t){case J:return Dt(n);case M:case q:return new e(+n);case X:case H:case Q:case nn:case tn:case rn:case en:case un:case on:return t=n.buffer,new e(r?Dt(t):t,n.byteOffset,n.length);case V:case G:return new e(n);case Y:var u=new e(n.source,kn.exec(n));u.lastIndex=n.lastIndex}return u}function Or(n,t,r){return null==n||Wr(t,n)||(t=Dr(t),n=1==t.length?n:yt(n,Et(t,0,-1)),t=Zr(t)),t=null==n?n:n[t],null==t?w:t.apply(n,r)}function Er(n){return null!=n&&Sr(Bu(n)); +}function Cr(n,t){return n=typeof n=="number"||On.test(n)?+n:-1,t=null==t?Cu:t,-1<n&&0==n%1&&n<t}function Ur(n,t,r){if(!ge(r))return false;var e=typeof t;return("number"==e?Er(r)&&Cr(t,r.length):"string"==e&&t in r)?(t=r[t],n===n?n===t:t!==t):false}function Wr(n,t){var r=typeof n;return"string"==r&&dn.test(n)||"number"==r?true:Oo(n)?false:!yn.test(n)||null!=t&&n in Br(t)}function $r(n){var t=br(n),r=Nn[t];return typeof r=="function"&&t in zn.prototype?n===r?true:(t=zu(r),!!t&&n===t[0]):false}function Sr(n){return typeof n=="number"&&-1<n&&0==n%1&&n<=Cu; +}function Fr(n,t){return n===w?t:Eo(n,t,Fr)}function Nr(n,t){n=Br(n);for(var r=-1,e=t.length,u={};++r<e;){var o=t[r];o in n&&(u[o]=n[o])}return u}function Tr(n,t){var r={};return ht(n,function(n,e,u){t(n,e,u)&&(r[e]=n)}),r}function Lr(n){for(var t=Re(n),r=t.length,e=r&&n.length,u=!!e&&Sr(e)&&(Oo(n)||pe(n)),o=-1,i=[];++o<r;){var f=t[o];(u&&Cr(f,e)||nu.call(n,f))&&i.push(f)}return i}function zr(n){return null==n?[]:Er(n)?ge(n)?n:Ve(n):Ee(n)}function Br(n){return ge(n)?n:Ve(n)}function Dr(n){if(Oo(n))return n; +var t=[];return u(n).replace(mn,function(n,r,e,u){t.push(e?u.replace(An,"$1"):r||n)}),t}function Mr(n){return n instanceof zn?n.clone():new Ln(n.__wrapped__,n.__chain__,qn(n.__actions__))}function qr(n,t,r){return n&&n.length?((r?Ur(n,t,r):null==t)&&(t=1),Et(n,0>t?0:t)):[]}function Pr(n,t,r){var e=n?n.length:0;return e?((r?Ur(n,t,r):null==t)&&(t=1),t=e-(+t||0),Et(n,0,0>t?0:t)):[]}function Kr(n){return n?n[0]:w}function Vr(n,t,e){var u=n?n.length:0;if(!u)return-1;if(typeof e=="number")e=0>e?bu(u+e,0):e;else if(e)return e=Lt(n,t), +e<u&&(t===t?t===n[e]:n[e]!==n[e])?e:-1;return r(n,t,e||0)}function Zr(n){var t=n?n.length:0;return t?n[t-1]:w}function Yr(n){return qr(n,1)}function Gr(n,t,e,u){if(!n||!n.length)return[];null!=t&&typeof t!="boolean"&&(u=e,e=Ur(n,t,u)?w:t,t=false);var o=wr();if((null!=e||o!==ut)&&(e=o(e,u,3)),t&&xr()===r){t=e;var i;e=-1,u=n.length;for(var o=-1,f=[];++e<u;){var a=n[e],c=t?t(a,e,n):a;e&&i===c||(i=c,f[++o]=a)}n=f}else n=St(n,e);return n}function Jr(n){if(!n||!n.length)return[];var t=-1,r=0;n=Vn(n,function(n){ +return Er(n)?(r=bu(n.length,r),true):void 0});for(var e=Be(r);++t<r;)e[t]=Gn(n,jt(t));return e}function Xr(n,t,r){return n&&n.length?(n=Jr(n),null==t?n:(t=Bt(t,r,4),Gn(n,function(n){return Xn(n,t,w,true)}))):[]}function Hr(n,t){var r=-1,e=n?n.length:0,u={};for(!e||t||Oo(n[0])||(t=[]);++r<e;){var o=n[r];t?u[o]=t[r]:o&&(u[o[0]]=o[1])}return u}function Qr(n){return n=Nn(n),n.__chain__=true,n}function ne(n,t,r){return t.call(r,n)}function te(n,t,r){var e=Oo(n)?Kn:at;return r&&Ur(n,t,r)&&(t=w),(typeof t!="function"||r!==w)&&(t=wr(t,r,3)), +e(n,t)}function re(n,t,r){var e=Oo(n)?Vn:lt;return t=wr(t,r,3),e(n,t)}function ee(n,t,r,e){var u=n?Bu(n):0;return Sr(u)||(n=Ee(n),u=n.length),r=typeof r!="number"||e&&Ur(t,r,e)?0:0>r?bu(u+r,0):r||0,typeof n=="string"||!Oo(n)&&be(n)?r<=u&&-1<n.indexOf(t,r):!!u&&-1<xr(n,t,r)}function ue(n,t,r){var e=Oo(n)?Gn:wt;return t=wr(t,r,3),e(n,t)}function oe(n,t,r){if(r?Ur(n,t,r):null==t){n=zr(n);var e=n.length;return 0<e?n[Rt(0,e-1)]:w}r=-1,n=je(n);var e=n.length,u=e-1;for(t=xu(0>t?0:+t||0,e);++r<t;){var e=Rt(r,u),o=n[e]; +n[e]=n[r],n[r]=o}return n.length=t,n}function ie(n,t,r){var e=Oo(n)?Hn:Ct;return r&&Ur(n,t,r)&&(t=w),(typeof t!="function"||r!==w)&&(t=wr(t,r,3)),e(n,t)}function fe(n,t){var r;if(typeof t!="function"){if(typeof n!="function")throw new Ge(L);var e=n;n=t,t=e}return function(){return 0<--n&&(r=t.apply(this,arguments)),1>=n&&(t=w),r}}function ae(n,t,r){function e(t,r){r&&iu(r),a=p=h=w,t&&(_=ho(),c=n.apply(s,f),p||a||(f=s=w))}function u(){var n=t-(ho()-l);0>=n||n>t?e(h,a):p=su(u,n)}function o(){e(g,p); +}function i(){if(f=arguments,l=ho(),s=this,h=g&&(p||!y),false===v)var r=y&&!p;else{a||y||(_=l);var e=v-(l-_),i=0>=e||e>v;i?(a&&(a=iu(a)),_=l,c=n.apply(s,f)):a||(a=su(o,e))}return i&&p?p=iu(p):p||t===v||(p=su(u,t)),r&&(i=true,c=n.apply(s,f)),!i||p||a||(f=s=w),c}var f,a,c,l,s,p,h,_=0,v=false,g=true;if(typeof n!="function")throw new Ge(L);if(t=0>t?0:+t||0,true===r)var y=true,g=false;else ge(r)&&(y=!!r.leading,v="maxWait"in r&&bu(+r.maxWait||0,t),g="trailing"in r?!!r.trailing:g);return i.cancel=function(){p&&iu(p),a&&iu(a), +_=0,a=p=h=w},i}function ce(n,t){function r(){var e=arguments,u=t?t.apply(this,e):e[0],o=r.cache;return o.has(u)?o.get(u):(e=n.apply(this,e),r.cache=o.set(u,e),e)}if(typeof n!="function"||t&&typeof t!="function")throw new Ge(L);return r.cache=new ce.Cache,r}function le(n,t){if(typeof n!="function")throw new Ge(L);return t=bu(t===w?n.length-1:+t||0,0),function(){for(var r=arguments,e=-1,u=bu(r.length-t,0),o=Be(u);++e<u;)o[e]=r[t+e];switch(t){case 0:return n.call(this,o);case 1:return n.call(this,r[0],o); +case 2:return n.call(this,r[0],r[1],o)}for(u=Be(t+1),e=-1;++e<t;)u[e]=r[e];return u[t]=o,n.apply(this,u)}}function se(n,t){return n>t}function pe(n){return h(n)&&Er(n)&&nu.call(n,"callee")&&!cu.call(n,"callee")}function he(n,t,r,e){return e=(r=typeof r=="function"?Bt(r,e,3):w)?r(n,t):w,e===w?dt(n,t,r):!!e}function _e(n){return h(n)&&typeof n.message=="string"&&ru.call(n)==P}function ve(n){return ge(n)&&ru.call(n)==K}function ge(n){var t=typeof n;return!!n&&("object"==t||"function"==t)}function ye(n){ +return null==n?false:ve(n)?uu.test(Qe.call(n)):h(n)&&Rn.test(n)}function de(n){return typeof n=="number"||h(n)&&ru.call(n)==V}function me(n){var t;if(!h(n)||ru.call(n)!=Z||pe(n)||!(nu.call(n,"constructor")||(t=n.constructor,typeof t!="function"||t instanceof t)))return false;var r;return ht(n,function(n,t){r=t}),r===w||nu.call(n,r)}function we(n){return ge(n)&&ru.call(n)==Y}function be(n){return typeof n=="string"||h(n)&&ru.call(n)==G}function xe(n){return h(n)&&Sr(n.length)&&!!Sn[ru.call(n)]}function Ae(n,t){ +return n<t}function je(n){var t=n?Bu(n):0;return Sr(t)?t?qn(n):[]:Ee(n)}function ke(n){return et(n,Re(n))}function Ie(n){return gt(n,Re(n))}function Re(n){if(null==n)return[];ge(n)||(n=Ve(n));for(var t=n.length,t=t&&Sr(t)&&(Oo(n)||pe(n))&&t||0,r=n.constructor,e=-1,r=typeof r=="function"&&r.prototype===n,u=Be(t),o=0<t;++e<t;)u[e]=e+"";for(var i in n)o&&Cr(i,t)||"constructor"==i&&(r||!nu.call(n,i))||u.push(i);return u}function Oe(n){n=Br(n);for(var t=-1,r=zo(n),e=r.length,u=Be(e);++t<e;){var o=r[t]; +u[t]=[o,n[o]]}return u}function Ee(n){return Ft(n,zo(n))}function Ce(n){return(n=u(n))&&n.replace(En,a).replace(xn,"")}function Ue(n,t){var r="";if(n=u(n),t=+t,1>t||!n||!mu(t))return r;do t%2&&(r+=n),t=yu(t/2),n+=n;while(t);return r}function We(n,t,r){var e=n;return(n=u(n))?(r?Ur(e,t,r):null==t)?n.slice(g(n),y(n)+1):(t+="",n.slice(o(n,t),i(n,t)+1)):n}function $e(n,t,r){return r&&Ur(n,t,r)&&(t=w),n=u(n),n.match(t||Wn)||[]}function Se(n,t,r){return r&&Ur(n,t,r)&&(t=w),h(n)?Ne(n):ut(n,t)}function Fe(n){ +return n}function Ne(n){return bt(ot(n,true))}function Te(n,t,r){if(null==r){var e=ge(t),u=e?zo(t):w;((u=u&&u.length?gt(t,u):w)?u.length:e)||(u=false,r=t,t=n,n=this)}u||(u=gt(t,zo(t)));var o=true,e=-1,i=ve(n),f=u.length;false===r?o=false:ge(r)&&"chain"in r&&(o=r.chain);for(;++e<f;){r=u[e];var a=t[r];n[r]=a,i&&(n.prototype[r]=function(t){return function(){var r=this.__chain__;if(o||r){var e=n(this.__wrapped__);return(e.__actions__=qn(this.__actions__)).push({func:t,args:arguments,thisArg:n}),e.__chain__=r,e}return t.apply(n,Jn([this.value()],arguments)); +}}(a))}return n}function Le(){}function ze(n){return Wr(n)?jt(n):kt(n)}_=_?Yn.defaults(Zn.Object(),_,Yn.pick(Zn,$n)):Zn;var Be=_.Array,De=_.Date,Me=_.Error,qe=_.Function,Pe=_.Math,Ke=_.Number,Ve=_.Object,Ze=_.RegExp,Ye=_.String,Ge=_.TypeError,Je=Be.prototype,Xe=Ve.prototype,He=Ye.prototype,Qe=qe.prototype.toString,nu=Xe.hasOwnProperty,tu=0,ru=Xe.toString,eu=Zn._,uu=Ze("^"+Qe.call(nu).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ou=_.ArrayBuffer,iu=_.clearTimeout,fu=_.parseFloat,au=Pe.pow,cu=Xe.propertyIsEnumerable,lu=jr(_,"Set"),su=_.setTimeout,pu=Je.splice,hu=_.Uint8Array,_u=jr(_,"WeakMap"),vu=Pe.ceil,gu=jr(Ve,"create"),yu=Pe.floor,du=jr(Be,"isArray"),mu=_.isFinite,wu=jr(Ve,"keys"),bu=Pe.max,xu=Pe.min,Au=jr(De,"now"),ju=_.parseInt,ku=Pe.random,Iu=Ke.NEGATIVE_INFINITY,Ru=Ke.POSITIVE_INFINITY,Ou=4294967294,Eu=2147483647,Cu=9007199254740991,Uu=_u&&new _u,Wu={}; +Nn.support={},Nn.templateSettings={escape:_n,evaluate:vn,interpolate:gn,variable:"",imports:{_:Nn}};var $u=function(){function n(){}return function(t){if(ge(t)){n.prototype=t;var r=new n;n.prototype=w}return r||{}}}(),Su=Vt(_t),Fu=Vt(vt,true),Nu=Zt(),Tu=Zt(true),Lu=Uu?function(n,t){return Uu.set(n,t),n}:Fe,zu=Uu?function(n){return Uu.get(n)}:Le,Bu=jt("length"),Du=function(){var n=0,t=0;return function(r,e){var u=ho(),o=S-(u-t);if(t=u,0<o){if(++n>=$)return r}else n=0;return Lu(r,e)}}(),Mu=le(function(n,t){ +return h(n)&&Er(n)?ft(n,pt(t,false,true)):[]}),qu=tr(),Pu=tr(true),Ku=le(function(n){for(var t=n.length,e=t,u=Be(l),o=xr(),i=o===r,f=[];e--;){var a=n[e]=Er(a=n[e])?a:[];u[e]=i&&120<=a.length&&gu&&lu?new Dn(e&&a):null}var i=n[0],c=-1,l=i?i.length:0,s=u[0];n:for(;++c<l;)if(a=i[c],0>(s?Mn(s,a):o(f,a,0))){for(e=t;--e;){var p=u[e];if(0>(p?Mn(p,a):o(n[e],a,0)))continue n}s&&s.push(a),f.push(a)}return f}),Vu=le(function(t,r){r=pt(r);var e=rt(t,r);return It(t,r.sort(n)),e}),Zu=vr(),Yu=vr(true),Gu=le(function(n){return St(pt(n,false,true)); +}),Ju=le(function(n,t){return Er(n)?ft(n,t):[]}),Xu=le(Jr),Hu=le(function(n){var t=n.length,r=2<t?n[t-2]:w,e=1<t?n[t-1]:w;return 2<t&&typeof r=="function"?t-=2:(r=1<t&&typeof e=="function"?(--t,e):w,e=w),n.length=t,Xr(n,r,e)}),Qu=le(function(n){return n=pt(n),this.thru(function(t){t=Oo(t)?t:[Br(t)];for(var r=n,e=-1,u=t.length,o=-1,i=r.length,f=Be(u+i);++e<u;)f[e]=t[e];for(;++o<i;)f[e++]=r[o];return f})}),no=le(function(n,t){return rt(n,pt(t))}),to=Pt(function(n,t,r){nu.call(n,r)?++n[r]:n[r]=1}),ro=nr(Su),eo=nr(Fu,true),uo=ur(Pn,Su),oo=ur(function(n,t){ +for(var r=n.length;r--&&false!==t(n[r],r,n););return n},Fu),io=Pt(function(n,t,r){nu.call(n,r)?n[r].push(t):n[r]=[t]}),fo=Pt(function(n,t,r){n[r]=t}),ao=le(function(n,t,r){var e=-1,u=typeof t=="function",o=Wr(t),i=Er(n)?Be(n.length):[];return Su(n,function(n){var f=u?t:o&&null!=n?n[t]:w;i[++e]=f?f.apply(n,r):Or(n,t,r)}),i}),co=Pt(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]}),lo=lr(Xn,Su),so=lr(function(n,t,r,e){var u=n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r},Fu),po=le(function(n,t){ +if(null==n)return[];var r=t[2];return r&&Ur(t[0],t[1],r)&&(t.length=1),Wt(n,pt(t),[])}),ho=Au||function(){return(new De).getTime()},_o=le(function(n,t,r){var e=x;if(r.length)var u=v(r,_o.placeholder),e=e|R;return gr(n,e,t,r,u)}),vo=le(function(n,t){t=t.length?pt(t):Ie(n);for(var r=-1,e=t.length;++r<e;){var u=t[r];n[u]=gr(n[u],x,n)}return n}),go=le(function(n,t,r){var e=x|A;if(r.length)var u=v(r,go.placeholder),e=e|R;return gr(t,e,n,r,u)}),yo=Xt(k),mo=Xt(I),wo=le(function(n,t){return it(n,1,t)}),bo=le(function(n,t,r){ +return it(n,t,r)}),xo=er(),Ao=er(true),jo=le(function(n,t){if(t=pt(t),typeof n!="function"||!Kn(t,e))throw new Ge(L);var r=t.length;return le(function(e){for(var u=xu(e.length,r);u--;)e[u]=t[u](e[u]);return n.apply(this,e)})}),ko=cr(R),Io=cr(O),Ro=le(function(n,t){return gr(n,C,w,w,w,pt(t))}),Oo=du||function(n){return h(n)&&Sr(n.length)&&ru.call(n)==D},Eo=Kt(At),Co=Kt(function(n,t,r){return r?nt(n,t,r):tt(n,t)}),Uo=Ht(Co,function(n,t){return n===w?t:n}),Wo=Ht(Eo,Fr),$o=rr(_t),So=rr(vt),Fo=or(Nu),No=or(Tu),To=ir(_t),Lo=ir(vt),zo=wu?function(n){ +var t=null==n?w:n.constructor;return typeof t=="function"&&t.prototype===n||typeof n!="function"&&Er(n)?Lr(n):ge(n)?wu(n):[]}:Lr,Bo=fr(true),Do=fr(),Mo=le(function(n,t){if(null==n)return{};if("function"!=typeof t[0])return t=Gn(pt(t),Ye),Nr(n,ft(Re(n),t));var r=Bt(t[0],t[1],3);return Tr(n,function(n,t,e){return!r(n,t,e)})}),qo=le(function(n,t){return null==n?{}:"function"==typeof t[0]?Tr(n,Bt(t[0],t[1],3)):Nr(n,pt(t))}),Po=Gt(function(n,t,r){return t=t.toLowerCase(),n+(r?t.charAt(0).toUpperCase()+t.slice(1):t); +}),Ko=Gt(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Vo=ar(),Zo=ar(true),Yo=Gt(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),Go=Gt(function(n,t,r){return n+(r?" ":"")+(t.charAt(0).toUpperCase()+t.slice(1))}),Jo=le(function(n,t){try{return n.apply(w,t)}catch(r){return _e(r)?r:new Me(r)}}),Xo=le(function(n,t){return function(r){return Or(r,n,t)}}),Ho=le(function(n,t){return function(r){return Or(n,r,t)}}),Qo=_r("ceil"),ni=_r("floor"),ti=Qt(se,Iu),ri=Qt(Ae,Ru),ei=_r("round");return Nn.prototype=Tn.prototype, +Ln.prototype=$u(Tn.prototype),Ln.prototype.constructor=Ln,zn.prototype=$u(Tn.prototype),zn.prototype.constructor=zn,Bn.prototype["delete"]=function(n){return this.has(n)&&delete this.__data__[n]},Bn.prototype.get=function(n){return"__proto__"==n?w:this.__data__[n]},Bn.prototype.has=function(n){return"__proto__"!=n&&nu.call(this.__data__,n)},Bn.prototype.set=function(n,t){return"__proto__"!=n&&(this.__data__[n]=t),this},Dn.prototype.push=function(n){var t=this.data;typeof n=="string"||ge(n)?t.set.add(n):t.hash[n]=true; +},ce.Cache=Bn,Nn.after=function(n,t){if(typeof t!="function"){if(typeof n!="function")throw new Ge(L);var r=n;n=t,t=r}return n=mu(n=+n)?n:0,function(){return 1>--n?t.apply(this,arguments):void 0}},Nn.ary=function(n,t,r){return r&&Ur(n,t,r)&&(t=w),t=n&&null==t?n.length:bu(+t||0,0),gr(n,E,w,w,w,w,t)},Nn.assign=Co,Nn.at=no,Nn.before=fe,Nn.bind=_o,Nn.bindAll=vo,Nn.bindKey=go,Nn.callback=Se,Nn.chain=Qr,Nn.chunk=function(n,t,r){t=(r?Ur(n,t,r):null==t)?1:bu(yu(t)||1,1),r=0;for(var e=n?n.length:0,u=-1,o=Be(vu(e/t));r<e;)o[++u]=Et(n,r,r+=t); +return o},Nn.compact=function(n){for(var t=-1,r=n?n.length:0,e=-1,u=[];++t<r;){var o=n[t];o&&(u[++e]=o)}return u},Nn.constant=function(n){return function(){return n}},Nn.countBy=to,Nn.create=function(n,t,r){var e=$u(n);return r&&Ur(n,t,r)&&(t=w),t?tt(e,t):e},Nn.curry=yo,Nn.curryRight=mo,Nn.debounce=ae,Nn.defaults=Uo,Nn.defaultsDeep=Wo,Nn.defer=wo,Nn.delay=bo,Nn.difference=Mu,Nn.drop=qr,Nn.dropRight=Pr,Nn.dropRightWhile=function(n,t,r){return n&&n.length?Nt(n,wr(t,r,3),true,true):[]},Nn.dropWhile=function(n,t,r){ +return n&&n.length?Nt(n,wr(t,r,3),true):[]},Nn.fill=function(n,t,r,e){var u=n?n.length:0;if(!u)return[];for(r&&typeof r!="number"&&Ur(n,t,r)&&(r=0,e=u),u=n.length,r=null==r?0:+r||0,0>r&&(r=-r>u?0:u+r),e=e===w||e>u?u:+e||0,0>e&&(e+=u),u=r>e?0:e>>>0,r>>>=0;r<u;)n[r++]=t;return n},Nn.filter=re,Nn.flatten=function(n,t,r){var e=n?n.length:0;return r&&Ur(n,t,r)&&(t=false),e?pt(n,t):[]},Nn.flattenDeep=function(n){return n&&n.length?pt(n,true):[]},Nn.flow=xo,Nn.flowRight=Ao,Nn.forEach=uo,Nn.forEachRight=oo,Nn.forIn=Fo, +Nn.forInRight=No,Nn.forOwn=To,Nn.forOwnRight=Lo,Nn.functions=Ie,Nn.groupBy=io,Nn.indexBy=fo,Nn.initial=function(n){return Pr(n,1)},Nn.intersection=Ku,Nn.invert=function(n,t,r){r&&Ur(n,t,r)&&(t=w),r=-1;for(var e=zo(n),u=e.length,o={};++r<u;){var i=e[r],f=n[i];t?nu.call(o,f)?o[f].push(i):o[f]=[i]:o[f]=i}return o},Nn.invoke=ao,Nn.keys=zo,Nn.keysIn=Re,Nn.map=ue,Nn.mapKeys=Bo,Nn.mapValues=Do,Nn.matches=Ne,Nn.matchesProperty=function(n,t){return xt(n,ot(t,true))},Nn.memoize=ce,Nn.merge=Eo,Nn.method=Xo,Nn.methodOf=Ho, +Nn.mixin=Te,Nn.modArgs=jo,Nn.negate=function(n){if(typeof n!="function")throw new Ge(L);return function(){return!n.apply(this,arguments)}},Nn.omit=Mo,Nn.once=function(n){return fe(2,n)},Nn.pairs=Oe,Nn.partial=ko,Nn.partialRight=Io,Nn.partition=co,Nn.pick=qo,Nn.pluck=function(n,t){return ue(n,ze(t))},Nn.property=ze,Nn.propertyOf=function(n){return function(t){return yt(n,Dr(t),t+"")}},Nn.pull=function(){var n=arguments,t=n[0];if(!t||!t.length)return t;for(var r=0,e=xr(),u=n.length;++r<u;)for(var o=0,i=n[r];-1<(o=e(t,i,o));)pu.call(t,o,1); +return t},Nn.pullAt=Vu,Nn.range=function(n,t,r){r&&Ur(n,t,r)&&(t=r=w),n=+n||0,r=null==r?1:+r||0,null==t?(t=n,n=0):t=+t||0;var e=-1;t=bu(vu((t-n)/(r||1)),0);for(var u=Be(t);++e<t;)u[e]=n,n+=r;return u},Nn.rearg=Ro,Nn.reject=function(n,t,r){var e=Oo(n)?Vn:lt;return t=wr(t,r,3),e(n,function(n,r,e){return!t(n,r,e)})},Nn.remove=function(n,t,r){var e=[];if(!n||!n.length)return e;var u=-1,o=[],i=n.length;for(t=wr(t,r,3);++u<i;)r=n[u],t(r,u,n)&&(e.push(r),o.push(u));return It(n,o),e},Nn.rest=Yr,Nn.restParam=le, +Nn.set=function(n,t,r){if(null==n)return n;var e=t+"";t=null!=n[e]||Wr(t,n)?[e]:Dr(t);for(var e=-1,u=t.length,o=u-1,i=n;null!=i&&++e<u;){var f=t[e];ge(i)&&(e==o?i[f]=r:null==i[f]&&(i[f]=Cr(t[e+1])?[]:{})),i=i[f]}return n},Nn.shuffle=function(n){return oe(n,Ru)},Nn.slice=function(n,t,r){var e=n?n.length:0;return e?(r&&typeof r!="number"&&Ur(n,t,r)&&(t=0,r=e),Et(n,t,r)):[]},Nn.sortBy=function(n,t,r){if(null==n)return[];r&&Ur(n,t,r)&&(t=w);var e=-1;return t=wr(t,r,3),n=wt(n,function(n,r,u){return{a:t(n,r,u), +b:++e,c:n}}),Ut(n,f)},Nn.sortByAll=po,Nn.sortByOrder=function(n,t,r,e){return null==n?[]:(e&&Ur(t,r,e)&&(r=w),Oo(t)||(t=null==t?[]:[t]),Oo(r)||(r=null==r?[]:[r]),Wt(n,t,r))},Nn.spread=function(n){if(typeof n!="function")throw new Ge(L);return function(t){return n.apply(this,t)}},Nn.take=function(n,t,r){return n&&n.length?((r?Ur(n,t,r):null==t)&&(t=1),Et(n,0,0>t?0:t)):[]},Nn.takeRight=function(n,t,r){var e=n?n.length:0;return e?((r?Ur(n,t,r):null==t)&&(t=1),t=e-(+t||0),Et(n,0>t?0:t)):[]},Nn.takeRightWhile=function(n,t,r){ +return n&&n.length?Nt(n,wr(t,r,3),false,true):[]},Nn.takeWhile=function(n,t,r){return n&&n.length?Nt(n,wr(t,r,3)):[]},Nn.tap=function(n,t,r){return t.call(r,n),n},Nn.throttle=function(n,t,r){var e=true,u=true;if(typeof n!="function")throw new Ge(L);return false===r?e=false:ge(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),ae(n,t,{leading:e,maxWait:+t,trailing:u})},Nn.thru=ne,Nn.times=function(n,t,r){if(n=yu(n),1>n||!mu(n))return[];var e=-1,u=Be(xu(n,4294967295));for(t=Bt(t,r,1);++e<n;)4294967295>e?u[e]=t(e):t(e); +return u},Nn.toArray=je,Nn.toPlainObject=ke,Nn.transform=function(n,t,r,e){var u=Oo(n)||xe(n);return t=wr(t,e,4),null==r&&(u||ge(n)?(e=n.constructor,r=u?Oo(n)?new e:[]:$u(ve(e)?e.prototype:w)):r={}),(u?Pn:_t)(n,function(n,e,u){return t(r,n,e,u)}),r},Nn.union=Gu,Nn.uniq=Gr,Nn.unzip=Jr,Nn.unzipWith=Xr,Nn.values=Ee,Nn.valuesIn=function(n){return Ft(n,Re(n))},Nn.where=function(n,t){return re(n,bt(t))},Nn.without=Ju,Nn.wrap=function(n,t){return t=null==t?Fe:t,gr(t,R,w,[n],[])},Nn.xor=function(){for(var n=-1,t=arguments.length;++n<t;){ +var r=arguments[n];if(Er(r))var e=e?Jn(ft(e,r),ft(r,e)):r}return e?St(e):[]},Nn.zip=Xu,Nn.zipObject=Hr,Nn.zipWith=Hu,Nn.backflow=Ao,Nn.collect=ue,Nn.compose=Ao,Nn.each=uo,Nn.eachRight=oo,Nn.extend=Co,Nn.iteratee=Se,Nn.methods=Ie,Nn.object=Hr,Nn.select=re,Nn.tail=Yr,Nn.unique=Gr,Te(Nn,Nn),Nn.add=function(n,t){return(+n||0)+(+t||0)},Nn.attempt=Jo,Nn.camelCase=Po,Nn.capitalize=function(n){return(n=u(n))&&n.charAt(0).toUpperCase()+n.slice(1)},Nn.ceil=Qo,Nn.clone=function(n,t,r,e){return t&&typeof t!="boolean"&&Ur(n,t,r)?t=false:typeof t=="function"&&(e=r, +r=t,t=false),typeof r=="function"?ot(n,t,Bt(r,e,3)):ot(n,t)},Nn.cloneDeep=function(n,t,r){return typeof t=="function"?ot(n,true,Bt(t,r,3)):ot(n,true)},Nn.deburr=Ce,Nn.endsWith=function(n,t,r){n=u(n),t+="";var e=n.length;return r=r===w?e:xu(0>r?0:+r||0,e),r-=t.length,0<=r&&n.indexOf(t,r)==r},Nn.escape=function(n){return(n=u(n))&&hn.test(n)?n.replace(sn,c):n},Nn.escapeRegExp=function(n){return(n=u(n))&&bn.test(n)?n.replace(wn,l):n||"(?:)"},Nn.every=te,Nn.find=ro,Nn.findIndex=qu,Nn.findKey=$o,Nn.findLast=eo, +Nn.findLastIndex=Pu,Nn.findLastKey=So,Nn.findWhere=function(n,t){return ro(n,bt(t))},Nn.first=Kr,Nn.floor=ni,Nn.get=function(n,t,r){return n=null==n?w:yt(n,Dr(t),t+""),n===w?r:n},Nn.gt=se,Nn.gte=function(n,t){return n>=t},Nn.has=function(n,t){if(null==n)return false;var r=nu.call(n,t);if(!r&&!Wr(t)){if(t=Dr(t),n=1==t.length?n:yt(n,Et(t,0,-1)),null==n)return false;t=Zr(t),r=nu.call(n,t)}return r||Sr(n.length)&&Cr(t,n.length)&&(Oo(n)||pe(n))},Nn.identity=Fe,Nn.includes=ee,Nn.indexOf=Vr,Nn.inRange=function(n,t,r){ +return t=+t||0,r===w?(r=t,t=0):r=+r||0,n>=xu(t,r)&&n<bu(t,r)},Nn.isArguments=pe,Nn.isArray=Oo,Nn.isBoolean=function(n){return true===n||false===n||h(n)&&ru.call(n)==M},Nn.isDate=function(n){return h(n)&&ru.call(n)==q},Nn.isElement=function(n){return!!n&&1===n.nodeType&&h(n)&&!me(n)},Nn.isEmpty=function(n){return null==n?true:Er(n)&&(Oo(n)||be(n)||pe(n)||h(n)&&ve(n.splice))?!n.length:!zo(n).length},Nn.isEqual=he,Nn.isError=_e,Nn.isFinite=function(n){return typeof n=="number"&&mu(n)},Nn.isFunction=ve,Nn.isMatch=function(n,t,r,e){ +return r=typeof r=="function"?Bt(r,e,3):w,mt(n,Ar(t),r)},Nn.isNaN=function(n){return de(n)&&n!=+n},Nn.isNative=ye,Nn.isNull=function(n){return null===n},Nn.isNumber=de,Nn.isObject=ge,Nn.isPlainObject=me,Nn.isRegExp=we,Nn.isString=be,Nn.isTypedArray=xe,Nn.isUndefined=function(n){return n===w},Nn.kebabCase=Ko,Nn.last=Zr,Nn.lastIndexOf=function(n,t,r){var e=n?n.length:0;if(!e)return-1;var u=e;if(typeof r=="number")u=(0>r?bu(e+r,0):xu(r||0,e-1))+1;else if(r)return u=Lt(n,t,true)-1,n=n[u],(t===t?t===n:n!==n)?u:-1; +if(t!==t)return p(n,u,true);for(;u--;)if(n[u]===t)return u;return-1},Nn.lt=Ae,Nn.lte=function(n,t){return n<=t},Nn.max=ti,Nn.min=ri,Nn.noConflict=function(){return Zn._=eu,this},Nn.noop=Le,Nn.now=ho,Nn.pad=function(n,t,r){n=u(n),t=+t;var e=n.length;return e<t&&mu(t)?(e=(t-e)/2,t=yu(e),e=vu(e),r=pr("",e,r),r.slice(0,t)+n+r):n},Nn.padLeft=Vo,Nn.padRight=Zo,Nn.parseInt=function(n,t,r){return(r?Ur(n,t,r):null==t)?t=0:t&&(t=+t),n=We(n),ju(n,t||(In.test(n)?16:10))},Nn.random=function(n,t,r){r&&Ur(n,t,r)&&(t=r=w); +var e=null==n,u=null==t;return null==r&&(u&&typeof n=="boolean"?(r=n,n=1):typeof t=="boolean"&&(r=t,u=true)),e&&u&&(t=1,u=false),n=+n||0,u?(t=n,n=0):t=+t||0,r||n%1||t%1?(r=ku(),xu(n+r*(t-n+fu("1e-"+((r+"").length-1))),t)):Rt(n,t)},Nn.reduce=lo,Nn.reduceRight=so,Nn.repeat=Ue,Nn.result=function(n,t,r){var e=null==n?w:n[t];return e===w&&(null==n||Wr(t,n)||(t=Dr(t),n=1==t.length?n:yt(n,Et(t,0,-1)),e=null==n?w:n[Zr(t)]),e=e===w?r:e),ve(e)?e.call(n):e},Nn.round=ei,Nn.runInContext=m,Nn.size=function(n){var t=n?Bu(n):0; +return Sr(t)?t:zo(n).length},Nn.snakeCase=Yo,Nn.some=ie,Nn.sortedIndex=Zu,Nn.sortedLastIndex=Yu,Nn.startCase=Go,Nn.startsWith=function(n,t,r){return n=u(n),r=null==r?0:xu(0>r?0:+r||0,n.length),n.lastIndexOf(t,r)==r},Nn.sum=function(n,t,r){if(r&&Ur(n,t,r)&&(t=w),t=wr(t,r,3),1==t.length){n=Oo(n)?n:zr(n),r=n.length;for(var e=0;r--;)e+=+t(n[r])||0;n=e}else n=$t(n,t);return n},Nn.template=function(n,t,r){var e=Nn.templateSettings;r&&Ur(n,t,r)&&(t=r=w),n=u(n),t=nt(tt({},r||t),e,Qn),r=nt(tt({},t.imports),e.imports,Qn); +var o,i,f=zo(r),a=Ft(r,f),c=0;r=t.interpolate||Cn;var l="__p+='";r=Ze((t.escape||Cn).source+"|"+r.source+"|"+(r===gn?jn:Cn).source+"|"+(t.evaluate||Cn).source+"|$","g");var p="sourceURL"in t?"//# sourceURL="+t.sourceURL+"\n":"";if(n.replace(r,function(t,r,e,u,f,a){return e||(e=u),l+=n.slice(c,a).replace(Un,s),r&&(o=true,l+="'+__e("+r+")+'"),f&&(i=true,l+="';"+f+";\n__p+='"),e&&(l+="'+((__t=("+e+"))==null?'':__t)+'"),c=a+t.length,t}),l+="';",(t=t.variable)||(l="with(obj){"+l+"}"),l=(i?l.replace(fn,""):l).replace(an,"$1").replace(cn,"$1;"), +l="function("+(t||"obj")+"){"+(t?"":"obj||(obj={});")+"var __t,__p=''"+(o?",__e=_.escape":"")+(i?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+l+"return __p}",t=Jo(function(){return qe(f,p+"return "+l).apply(w,a)}),t.source=l,_e(t))throw t;return t},Nn.trim=We,Nn.trimLeft=function(n,t,r){var e=n;return(n=u(n))?n.slice((r?Ur(e,t,r):null==t)?g(n):o(n,t+"")):n},Nn.trimRight=function(n,t,r){var e=n;return(n=u(n))?(r?Ur(e,t,r):null==t)?n.slice(0,y(n)+1):n.slice(0,i(n,t+"")+1):n; +},Nn.trunc=function(n,t,r){r&&Ur(n,t,r)&&(t=w);var e=U;if(r=W,null!=t)if(ge(t)){var o="separator"in t?t.separator:o,e="length"in t?+t.length||0:e;r="omission"in t?u(t.omission):r}else e=+t||0;if(n=u(n),e>=n.length)return n;if(e-=r.length,1>e)return r;if(t=n.slice(0,e),null==o)return t+r;if(we(o)){if(n.slice(e).search(o)){var i,f=n.slice(0,e);for(o.global||(o=Ze(o.source,(kn.exec(o)||"")+"g")),o.lastIndex=0;n=o.exec(f);)i=n.index;t=t.slice(0,null==i?e:i)}}else n.indexOf(o,e)!=e&&(o=t.lastIndexOf(o), +-1<o&&(t=t.slice(0,o)));return t+r},Nn.unescape=function(n){return(n=u(n))&&pn.test(n)?n.replace(ln,d):n},Nn.uniqueId=function(n){var t=++tu;return u(n)+t},Nn.words=$e,Nn.all=te,Nn.any=ie,Nn.contains=ee,Nn.eq=he,Nn.detect=ro,Nn.foldl=lo,Nn.foldr=so,Nn.head=Kr,Nn.include=ee,Nn.inject=lo,Te(Nn,function(){var n={};return _t(Nn,function(t,r){Nn.prototype[r]||(n[r]=t)}),n}(),false),Nn.sample=oe,Nn.prototype.sample=function(n){return this.__chain__||null!=n?this.thru(function(t){return oe(t,n)}):oe(this.value()); +},Nn.VERSION=b,Pn("bind bindKey curry curryRight partial partialRight".split(" "),function(n){Nn[n].placeholder=Nn}),Pn(["drop","take"],function(n,t){zn.prototype[n]=function(r){var e=this.__filtered__;if(e&&!t)return new zn(this);r=null==r?1:bu(yu(r)||0,0);var u=this.clone();return e?u.__takeCount__=xu(u.__takeCount__,r):u.__views__.push({size:r,type:n+(0>u.__dir__?"Right":"")}),u},zn.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}}),Pn(["filter","map","takeWhile"],function(n,t){ +var r=t+1,e=r!=T;zn.prototype[n]=function(n,t){var u=this.clone();return u.__iteratees__.push({iteratee:wr(n,t,1),type:r}),u.__filtered__=u.__filtered__||e,u}}),Pn(["first","last"],function(n,t){var r="take"+(t?"Right":"");zn.prototype[n]=function(){return this[r](1).value()[0]}}),Pn(["initial","rest"],function(n,t){var r="drop"+(t?"":"Right");zn.prototype[n]=function(){return this.__filtered__?new zn(this):this[r](1)}}),Pn(["pluck","where"],function(n,t){var r=t?"filter":"map",e=t?bt:ze;zn.prototype[n]=function(n){ +return this[r](e(n))}}),zn.prototype.compact=function(){return this.filter(Fe)},zn.prototype.reject=function(n,t){return n=wr(n,t,1),this.filter(function(t){return!n(t)})},zn.prototype.slice=function(n,t){n=null==n?0:+n||0;var r=this;return r.__filtered__&&(0<n||0>t)?new zn(r):(0>n?r=r.takeRight(-n):n&&(r=r.drop(n)),t!==w&&(t=+t||0,r=0>t?r.dropRight(-t):r.take(t-n)),r)},zn.prototype.takeRightWhile=function(n,t){return this.reverse().takeWhile(n,t).reverse()},zn.prototype.toArray=function(){return this.take(Ru); +},_t(zn.prototype,function(n,t){var r=/^(?:filter|map|reject)|While$/.test(t),e=/^(?:first|last)$/.test(t),u=Nn[e?"take"+("last"==t?"Right":""):t];u&&(Nn.prototype[t]=function(){function t(n){return e&&i?u(n,1)[0]:u.apply(w,Jn([n],o))}var o=e?[1]:arguments,i=this.__chain__,f=this.__wrapped__,a=!!this.__actions__.length,c=f instanceof zn,l=o[0],s=c||Oo(f);return s&&r&&typeof l=="function"&&1!=l.length&&(c=s=false),l={func:ne,args:[t],thisArg:w},a=c&&!a,e&&!i?a?(f=f.clone(),f.__actions__.push(l),n.call(f)):u.call(w,this.value())[0]:!e&&s?(f=a?f:new zn(this), +f=n.apply(f,o),f.__actions__.push(l),new Ln(f,i)):this.thru(t)})}),Pn("join pop push replace shift sort splice split unshift".split(" "),function(n){var t=(/^(?:replace|split)$/.test(n)?He:Je)[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:join|pop|replace|shift)$/.test(n);Nn.prototype[n]=function(){var n=arguments;return e&&!this.__chain__?t.apply(this.value(),n):this[r](function(r){return t.apply(r,n)})}}),_t(zn.prototype,function(n,t){var r=Nn[t];if(r){var e=r.name+"";(Wu[e]||(Wu[e]=[])).push({ +name:t,func:r})}}),Wu[sr(w,A).name]=[{name:"wrapper",func:w}],zn.prototype.clone=function(){var n=new zn(this.__wrapped__);return n.__actions__=qn(this.__actions__),n.__dir__=this.__dir__,n.__filtered__=this.__filtered__,n.__iteratees__=qn(this.__iteratees__),n.__takeCount__=this.__takeCount__,n.__views__=qn(this.__views__),n},zn.prototype.reverse=function(){if(this.__filtered__){var n=new zn(this);n.__dir__=-1,n.__filtered__=true}else n=this.clone(),n.__dir__*=-1;return n},zn.prototype.value=function(){ +var n,t=this.__wrapped__.value(),r=this.__dir__,e=Oo(t),u=0>r,o=e?t.length:0;n=o;for(var i=this.__views__,f=0,a=-1,c=i.length;++a<c;){var l=i[a],s=l.size;switch(l.type){case"drop":f+=s;break;case"dropRight":n-=s;break;case"take":n=xu(n,f+s);break;case"takeRight":f=bu(f,n-s)}}if(n={start:f,end:n},i=n.start,f=n.end,n=f-i,u=u?f:i-1,i=this.__iteratees__,f=i.length,a=0,c=xu(n,this.__takeCount__),!e||o<F||o==n&&c==n)return Tt(t,this.__actions__);e=[];n:for(;n--&&a<c;){for(u+=r,o=-1,l=t[u];++o<f;){var p=i[o],s=p.type,p=p.iteratee(l); +if(s==T)l=p;else if(!p){if(s==N)continue n;break n}}e[a++]=l}return e},Nn.prototype.chain=function(){return Qr(this)},Nn.prototype.commit=function(){return new Ln(this.value(),this.__chain__)},Nn.prototype.concat=Qu,Nn.prototype.plant=function(n){for(var t,r=this;r instanceof Tn;){var e=Mr(r);t?u.__wrapped__=e:t=e;var u=e,r=r.__wrapped__}return u.__wrapped__=n,t},Nn.prototype.reverse=function(){function n(n){return n.reverse()}var t=this.__wrapped__;return t instanceof zn?(this.__actions__.length&&(t=new zn(this)), +t=t.reverse(),t.__actions__.push({func:ne,args:[n],thisArg:w}),new Ln(t,this.__chain__)):this.thru(n)},Nn.prototype.toString=function(){return this.value()+""},Nn.prototype.run=Nn.prototype.toJSON=Nn.prototype.valueOf=Nn.prototype.value=function(){return Tt(this.__wrapped__,this.__actions__)},Nn.prototype.collect=Nn.prototype.map,Nn.prototype.head=Nn.prototype.first,Nn.prototype.select=Nn.prototype.filter,Nn.prototype.tail=Nn.prototype.rest,Nn}var w,b="3.10.1",x=1,A=2,j=4,k=8,I=16,R=32,O=64,E=128,C=256,U=30,W="...",$=150,S=16,F=200,N=1,T=2,L="Expected a function",z="__lodash_placeholder__",B="[object Arguments]",D="[object Array]",M="[object Boolean]",q="[object Date]",P="[object Error]",K="[object Function]",V="[object Number]",Z="[object Object]",Y="[object RegExp]",G="[object String]",J="[object ArrayBuffer]",X="[object Float32Array]",H="[object Float64Array]",Q="[object Int8Array]",nn="[object Int16Array]",tn="[object Int32Array]",rn="[object Uint8Array]",en="[object Uint8ClampedArray]",un="[object Uint16Array]",on="[object Uint32Array]",fn=/\b__p\+='';/g,an=/\b(__p\+=)''\+/g,cn=/(__e\(.*?\)|\b__t\))\+'';/g,ln=/&(?:amp|lt|gt|quot|#39|#96);/g,sn=/[&<>"'`]/g,pn=RegExp(ln.source),hn=RegExp(sn.source),_n=/<%-([\s\S]+?)%>/g,vn=/<%([\s\S]+?)%>/g,gn=/<%=([\s\S]+?)%>/g,yn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,dn=/^\w*$/,mn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,wn=/^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,bn=RegExp(wn.source),xn=/[\u0300-\u036f\ufe20-\ufe23]/g,An=/\\(\\)?/g,jn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,kn=/\w*$/,In=/^0[xX]/,Rn=/^\[object .+?Constructor\]$/,On=/^\d+$/,En=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Cn=/($^)/,Un=/['\n\r\u2028\u2029\\]/g,Wn=RegExp("[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?=[A-Z\\xc0-\\xd6\\xd8-\\xde][a-z\\xdf-\\xf6\\xf8-\\xff]+)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+|[A-Z\\xc0-\\xd6\\xd8-\\xde]+|[0-9]+","g"),$n="Array ArrayBuffer Date Error Float32Array Float64Array Function Int8Array Int16Array Int32Array Math Number Object RegExp Set String _ clearTimeout isFinite parseFloat parseInt setTimeout TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array WeakMap".split(" "),Sn={}; +Sn[X]=Sn[H]=Sn[Q]=Sn[nn]=Sn[tn]=Sn[rn]=Sn[en]=Sn[un]=Sn[on]=true,Sn[B]=Sn[D]=Sn[J]=Sn[M]=Sn[q]=Sn[P]=Sn[K]=Sn["[object Map]"]=Sn[V]=Sn[Z]=Sn[Y]=Sn["[object Set]"]=Sn[G]=Sn["[object WeakMap]"]=false;var Fn={};Fn[B]=Fn[D]=Fn[J]=Fn[M]=Fn[q]=Fn[X]=Fn[H]=Fn[Q]=Fn[nn]=Fn[tn]=Fn[V]=Fn[Z]=Fn[Y]=Fn[G]=Fn[rn]=Fn[en]=Fn[un]=Fn[on]=true,Fn[P]=Fn[K]=Fn["[object Map]"]=Fn["[object Set]"]=Fn["[object WeakMap]"]=false;var Nn={"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a", +"\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y", +"\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss"},Tn={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Ln={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},zn={"function":true,object:true},Bn={0:"x30",1:"x31",2:"x32",3:"x33",4:"x34",5:"x35",6:"x36",7:"x37",8:"x38",9:"x39",A:"x41",B:"x42",C:"x43",D:"x44",E:"x45",F:"x46",a:"x61",b:"x62",c:"x63",d:"x64",e:"x65",f:"x66",n:"x6e",r:"x72",t:"x74",u:"x75",v:"x76",x:"x78"},Dn={"\\":"\\", +"'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Mn=zn[typeof exports]&&exports&&!exports.nodeType&&exports,qn=zn[typeof module]&&module&&!module.nodeType&&module,Pn=zn[typeof self]&&self&&self.Object&&self,Kn=zn[typeof window]&&window&&window.Object&&window,Vn=qn&&qn.exports===Mn&&Mn,Zn=Mn&&qn&&typeof global=="object"&&global&&global.Object&&global||Kn!==(this&&this.window)&&Kn||Pn||this,Yn=m();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Zn._=Yn, define(function(){ +return Yn})):Mn&&qn?Vn?(qn.exports=Yn)._=Yn:Mn._=Yn:Zn._=Yn}).call(this);
\ No newline at end of file diff --git a/StoneIsland/www/js/vendor/oktween.js b/StoneIsland/www/js/vendor/oktween.js new file mode 100644 index 00000000..d0d2b7cb --- /dev/null +++ b/StoneIsland/www/js/vendor/oktween.js @@ -0,0 +1,124 @@ +/* + oktween.add({ + obj: el.style, + units: "px", + from: { left: 0 }, + to: { left: 100 }, + duration: 1000, + easing: oktween.easing.circ_out, + finish: function(){ + console.log("done") + } + }) +*/ + +var oktween = (function(){ + var oktween = {} + var tweens = oktween.tweens = [] + var last_t = 0 + var id = 0 + oktween.speed = 1 + oktween.then = oktween.add = function(tween){ + tween.id = id++ + tween.obj = tween.obj || {} + if (tween.easing) { + if (typeof tween.easing == "string") { + tween.easing = oktween.easing[tween.easing] + } + } + else { + tween.easing = oktween.easing.linear + } + if (! ('from' in tween) ) { + tween.from = {} + tween.keys = Object.keys(tween.to) + tween.keys.forEach(function(prop){ + tween.from[prop] = parseFloat(tween.obj[prop]) + }) + } + else { + tween.keys = Object.keys(tween.from) + } + tween.delay = tween.delay || 0 + tween.start = last_t + tween.delay + tween.done = false + tween.then = function(fn){ tween.after = [fn] } + tween.finish = function(){ tween.start = 0 } + tween.cancel = function(){ + var idx = tweens.indexOf(tween) + if (~idx) { tweens.splice(idx, 1) } + } + tween.tick = 0 + tween.skip = tween.skip || 1 + tweens.push(tween) + return tween + } + oktween.update = function(t) { + requestAnimationFrame(oktween.update) + last_t = t * oktween.speed + if (tweens.length == 0) return + var done = false + tweens.forEach(function(tween, i){ + var dt = Math.min(1.0, (t - tween.start) / tween.duration) + tween.tick++ + if (dt < 0 || (dt < 1 && (tween.tick % tween.skip != 0))) return + var ddt = tween.dt = tween.easing(dt) + tween.keys.forEach(function(prop){ + val = lerp( ddt, tween.from[prop], tween.to[prop] ) + if (tween.round) val = Math.round(val) + if (tween.units) val = (Math.round(val)) + tween.units + tween.obj[prop] = val + }) + tween.update && tween.update(tween.obj, dt) + if (dt == 1) { + tween.finished && tween.finished(tween) + tween.after && tween.after.forEach(function(twn){ + if (typeof twn == "function") { return twn() } + if (! twn.obj) { twn.obj = tween.obj } + oktween.add(twn) + }) + if (tween.loop) { + tween.start = t + tween.delay + } + else { + done = tween.done = true + } + } + }) + if (done) { + tweens = tweens.filter(function(tween){ return ! tween.done }) + } + } + function lerp(n,a,b){ return (b-a)*n+a } + + requestAnimationFrame(oktween.update) + + oktween.easing = { + linear: function(t){ + return t + }, + circ_out: function(t) { + return Math.sqrt(1 - (t = t - 1) * t) + }, + circ_in: function(t){ + return -(Math.sqrt(1 - (t * t)) - 1) + }, + circ_in_out: function(t) { + return ((t*=2) < 1) ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1) + }, + quad_in: function(n){ + return Math.pow(n, 2) + }, + quad_out: function(n){ + return n * (n - 2) * -1 + }, + quad_in_out: function(n){ + n = n * 2 + if(n < 1){ return Math.pow(n, 2) / 2 } + return -1 * ((--n) * (n - 2) - 1) / 2 + }, + + } + + return oktween +})() diff --git a/StoneIsland/www/js/vendor/util.js b/StoneIsland/www/js/vendor/util.js new file mode 100644 index 00000000..34ef45f8 --- /dev/null +++ b/StoneIsland/www/js/vendor/util.js @@ -0,0 +1,295 @@ +if (window.$) { + $.fn.int = function() { return parseInt($(this).val(),10) } + $.fn.float = function() { return parseFloat($(this).val()) } + $.fn.string = function() { return trim($(this).val()) } + $.fn.enable = function() { return $(this).attr("disabled",null) } + $.fn.disable = function() { return $(this).attr("disabled","disabled") } + $.fn.sanitize = function(s) { return trim(sanitize($(this).val())) } + $.fn.stripHTML = function(s) { return trim(stripHTML($(this).val())) } + $.fn.sanitizeName = function(s) { return trim(sanitizeName($(this).val())) } + $.fn.htmlSafe = function(s) { return $(this).html(sanitize(s)) } + $.fn.toDollars = function(i) { return $(this).html((i/100).toFixed(2)) } +} + +function trim (s){ return s.replace(/^\s+/,"").replace(/\s+$/,"") } +function sanitize (s){ return (s || "").replace(new RegExp("[<>&]", 'g'), "") } +function sanitizeName (s){ return (s || "").replace(new RegExp("[^-_a-zA-Z0-9]", 'g'), "") } +function stripHTML (s){ return (s || "").replace(/<[^>]+>/g, "") } +function sanitizeHTML (s){ return (s || "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") } +function capitalize (s){ return s.split(" ").map(capitalizeWord).join(" ") } +function capitalizeWord (s){ return s.charAt(0).toUpperCase() + s.slice(1) } +function slugify (s){ return (s || "").toLowerCase().replace(/\s/g,"-").replace(/[^-_a-zA-Z0-9]/g, '-').replace(/-+/g,"-") } +function rgb_string (rgb) { return "rgb(" + rgb.map(Math.round).join(",") + ")" } +function rgba_string (rgb,a) { return "rgba(" + rgb.map(Math.round).join(",") + "," + a + ")" } +function hex_string (rgb) { return "#" + rgb.map(Math.round).map(function(n){ var s = n.toString(16); return s.length == 1 ? "0"+s : s }).join("") } +function parse_rgba_string (s) { return s.match(/(\d+)/g).slice(0,3) } + +var E = Math.E +var PI = Math.PI +var PHI = (1+Math.sqrt(5))/2 +var TWO_PI = PI*2 +var HALF_PI = PI/2 +var LN10 = Math.LN10 +function clamp(n,a,b){ return n<a?a:n<b?n:b } +function norm(n,a,b){ return (n-a) / (b-a) } +function lerp(n,a,b){ return (b-a)*n+a } +function mix(n,a,b){ return a*(1-n)+b*n } +function ceil(n){ return Math.ceil(n) } +function floor(n){ return Math.floor(n) } +function round(n){ return Math.round(n) } +function quantize(n,a){ return round(n / a) * a } +function max(a,b){ return Math.max(a,b) } +function min(a,b){ return Math.min(a,b) } +function abs(n){ return Math.abs(n) } +function sign(n){ return n ? Math.abs(n)/n : 0 } +function pow(n,b) { return Math.pow(n,b) } +function exp(n) { return Math.exp(n) } +function log(n){ return Math.log(n) } +function ln(n){ return Math.log(n)/LN10 } +function sqrt(n) { return Math.sqrt(n) } +function cos(n){ return Math.cos(n) } +function sin(n){ return Math.sin(n) } +function tan(n){ return Math.tan(n) } +function acos(n){ return Math.cos(n) } +function asin(n){ return Math.sin(n) } +function atan(n){ return Math.atan(n) } +function atan2(a,b){ return Math.atan2(a,b) } +function sec(n){ return 1/cos(n) } +function csc(n){ return 1/sin(n) } +function cot(n){ return 1/tan(n) } +function cosp(n){ return (1+Math.cos(n))/2 } // cos^2 +function sinp(n){ return (1+Math.sin(n))/2 } +function random(){ return Math.random() } +function rand(n){ return (Math.random()*n) } +function randint(n){ return rand(n)|0 } +function randrange(a,b){ return a + rand(b-a) } +function choice(a){ return a[randint(a.length)] } +function deg(n){ return n*180/PI } +function rad(n){ return n*PI/180 } +function xor(a,b){ a=!!a; b=!!b; return (a||b) && !(a&&b) } +function mod(n,m){ return n-(m * floor(n/m)) } +function dist(x0,y0,x1,y1){ return sqrt(pow(x1-x0,2)+pow(y1-y0,2)) } +function angle(x0,y0,x1,y1){ return atan2(y1-y0,x1-x0) } +function avg(m,n,a){ return (m*(a-1)+n)/a } +function noop(){} + +function pixel(x,y){ return 4*(mod(y,actual_h)*actual_w+mod(x,actual_w)) } +function rgbpixel(d,x,y){ + var p = pixel(~~x,~~y) + r = d[p] + g = d[p+1] + b = d[p+2] + a = d[p+3] +} +function fit(d,x,y){ rgbpixel(d,x*actual_w/w,y*actual_h/h) } + +function step(a, b){ + return (b >= a) + 0 + // ^^ bool -> int +} + +function julestep (a,b,n) { + return clamp(norm(n,a,b), 0.0, 1.0); +} + +// hermite curve apparently +function smoothstep(min,max,n){ + var t = clamp((n - min) / (max - min), 0.0, 1.0); + return t * t * (3.0 - 2.0 * t) +} + +function shuffle(a){ + var r, swap + for (var i = a.length; i > 0; i--){ + r = randint(i) + swap = a[i-1] + a[i-1] = a[r] + a[r] = swap + } + return a +} +function reverse(a){ + var reversed = [] + for (var i = 0, _len = a.length-1; i <= _len; i++){ + reversed[i] = a[_len-i] + } + return reversed +} +function deinterlace(a){ + var odd = [], even = [] + for (var i = 0, _len = a.length; i < _len; i++) { + if (i % 2) even.push(a[i]) + else odd.push(a[i]) + } + return [even, odd] +} +function weave(a){ + var aa = deinterlace(a) + var b = [] + aa[0].forEach(function(el){ b.push(el) }) + reverse(aa[1]).forEach(function(el){ b.push(el) }) + return b +} +function range(m,n,s){ + var a = [] + s = s || 1 + for (var i = m; i <= n; i += s) { + a.push(i) + } + return a +} + +var guid_syllables = "iz az ez or iv ex baz el lo lum ot un no".split(" ") +var guid_n = 0 +function guid(n){ + var len = guid_syllables.length + return ((++guid_n*(len-1)*(~~log(guid_n))).toString(len)).split("").map(function(s){ + return guid_syllables[parseInt(s, len) % len--] + }).join("") +} + +function defaults (dest, src) { + dest = dest || {} + for (var i in src) { + dest[i] = typeof dest[i] == 'undefined' ? src[i] : dest[i] + } + return dest +} + +// Change straight quotes to curly and double hyphens to em-dashes. +function smarten(a) { + a = a.replace(/(^|[-\u2014\s(\["])'/g, "$1\u2018"); // opening singles + a = a.replace(/'/g, "\u2019"); // closing singles & apostrophes + a = a.replace(/(^|[-\u2014/\[(\u2018\s])"/g, "$1\u201c"); // opening doubles + a = a.replace(/"/g, "\u201d"); // closing doubles + a = a.replace(/--/g, "\u2014"); // em-dashes + return a +}; + + +function pairs(h){ + var a = [] + for (var i in h) { + if(h.hasOwnProperty(i)) { + a.push([i, h[i]]) + } + } + return a +} +function invert_hash (h) { + var k = {} + for (var i in h) { if (h.hasOwnProperty(i)) k[h[i]] = i } + return k +} +function filenameFromUrl (url) { + var partz = url.split( "/" ) + return partz[partz.length-1].split(".")[0] +} + +function bitcount(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +// Function.bind polyfill +if (!Function.prototype.bind) { + Function.prototype.bind = function(oThis) { + if (typeof this !== 'function') { + // closest thing possible to the ECMAScript 5 + // internal IsCallable function + throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function() {}, + fBound = function() { + return fToBind.apply(this instanceof fNOP && oThis + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + fNOP.prototype = this.prototype; + fBound.prototype = new fNOP(); + + return fBound; + }; +} + +// rAF polyfill +(function() { + var lastTime = 0; + var vendors = ['ms', 'moz', 'webkit', 'o']; + for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] + || window[vendors[x]+'CancelRequestAnimationFrame']; + } + + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function(callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function() { callback(currTime + timeToCall); }, + timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function(id) { + clearTimeout(id); + }; +}()); + +// Identify browser based on useragent string +(function( ua ) { + ua = ua.toLowerCase(); + var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || + /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || + []; + var matched = { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + browser = {}; + if ( matched.browser ) { + browser[ matched.browser ] = true; + browser.version = matched.version; + } + // Chrome is Webkit, but Webkit is also Safari. + if ( browser.chrome ) { + browser.webkit = true; + } else if ( browser.webkit ) { + browser.safari = true; + } + if (window.$) $.browser = browser; + return browser; +})( navigator.userAgent ); + +// Naive useragent detection pattern +var is_iphone = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) +var is_ipad = (navigator.userAgent.match(/iPad/i)) +var is_android = (navigator.userAgent.match(/Android/i)) +var is_mobile = is_iphone || is_ipad || is_android +var is_desktop = ! is_mobile; +var app_devicePixelRatio = is_mobile ? devicePixelRatio : 1; + +function selectElementContents(el) { + if (window.getSelection && document.createRange) { + var sel = window.getSelection(); + var range = document.createRange(); + range.selectNodeContents(el); + sel.removeAllRanges(); + sel.addRange(range); + } else if (document.selection && document.body.createTextRange) { + var textRange = document.body.createTextRange(); + textRange.moveToElementText(el); + textRange.select(); + } +} diff --git a/StoneIsland/www/js/vendor/view/formview.js b/StoneIsland/www/js/vendor/view/formview.js new file mode 100644 index 00000000..8cd222e3 --- /dev/null +++ b/StoneIsland/www/js/vendor/view/formview.js @@ -0,0 +1,146 @@ +var FormView = View.extend({ + + method: "post", + useMinotaur: false, + + events: { + "submit form": "save" + }, + + initialize: function(opt){ + if (opt && opt.parent) { + this.parent = opt.parent + } + this.$form = this.$("form") + this.$errors = this.$(".errors") + this.$errorList = this.$(".errorList") + }, + + reset: function(){ + this.$("input,textarea").not("[type='submit']").not("[type='hidden']").val("") + }, + + showErrors: function(errors){ + if (errors && errors.length) { + this.$errorList.empty(); + for (var i in errors) { + this.$errorList.append('<div>' + errors[i] + '</div>'); + } + this.$errors.css("opacity", 1.0); + setTimeout(function(){ + this.$errors.show().css("opacity", 1.0); + }.bind(this), 200) + } + }, + + serialize: function(){ + var fd = new FormData(), hasCSRF = false + + this.$("input[name], select[name], textarea[name]").each( function(){ + if (this.type == "file") { + if (this.files.length > 0) { + fd.append(this.name, this.files[0]); + } + } +// else if (this.type == "password") { +// if (this.value.length > 0) { +// fd.append(this.name, SHA1.hex('bucky$' + this.value + '$bucky')) +// } +// } + else { + fd.append(this.name, this.value); + hasCSRF = hasCSRF || this.name == "_csrf" + } + }); + +// if (! hasCSRF) { +// fd.append("_csrf", $("[name=_csrf]").attr("value")) +// } +// + return fd + }, + + save: function(e, successCallback, errorCallback){ + e && e.preventDefault() + + this.$errors.hide().css("opacity", 0.0); + + if (this.validate) { + var errors = this.validate() + if (errors && errors.length) { + if (errorCallback) { + errorCallback(errors) + } + else { + this.showErrors(errors) + } + return + } + } + + var action = typeof this.action == "function" ? this.action() : this.action + if (! action) return + + var request = $.ajax({ + url: action, + type: this.method, + data: this.serialize(), +// headers: { "csrf-token": $("[name=_csrf]").attr("value") }, + dataType: "json", + processData: false, + contentType: false, + success: function(response){ + + if (response.error) { + var errors = [] + for (var key in response.error.errors) { + errors.push(response.error.errors[key].message); + } + if (errorCallback) { + errorCallback(errors) + } + else { + this.showErrors(errors) + } + return + } + else { + if (successCallback) { + successCallback(response) + } + if (this.success) { + this.success(response) + } + } + + + }.bind(this), + error: function(response){ + }.bind(this), + complete: function(response){ + if (this.useMinotaur) { + Minotaur.hide() + } + }.bind(this), + }) + + if (this.useMinotaur) { + Minotaur.show() + } + + }, + +}) + +/* + +var ModalFormView = ModalView.extend(FormView.prototype).extend({ + + load: function(){ + this.reset() + this.show() + } + +}) + +*/
\ No newline at end of file diff --git a/StoneIsland/www/js/vendor/view/router.js b/StoneIsland/www/js/vendor/view/router.js new file mode 100644 index 00000000..36f86b5d --- /dev/null +++ b/StoneIsland/www/js/vendor/view/router.js @@ -0,0 +1,67 @@ +var Router = View.extend({ + + go: function(url){ + this.parseRoute(url) + }, + + route: function(){ + this.originalPath = window.location.pathname + this.parseRoute(window.location.pathname) + }, + + parseRoute: function(pathname){ + + var routes = is_mobile ? this.mobileRoutes : this.routes, + path = pathname.split("/"); + + for (var i = 0; i < path.length; i++) { + if (! path[i].length) { + path[i] = null + } + } + + if (pathname in routes) { + this[this.routes[pathname]]() + return + } + + if (path[path.length-1] == null) { + path.pop() + } + + for (var route in routes) { + var routePath = route.split("/") + if (routePath[1] == path[1]) { + if (routePath[2] && routePath[2].indexOf(":") !== -1 && path[2] && (path[3] === routePath[3]) ) { + this[this.routes[route]](path[2]) + return + } + else if (routePath[2] == path[2]) { + if (routePath[3] && path[3]) { + if (routePath[3].indexOf(":") !== -1) { + this[this.routes[route]](path[3]) + return + } + else if (routePath[3] == path[3]) { + this[this.routes[route]]() + return + } + } + else if (! routePath[3] && ! path[3]) { + this[this.routes[route]]() + return + } + } + else if (! routePath[2] && (! path[2].length || ! path[2])) { + this[this.routes[route]]() + return + } + } + } + + if (is_mobile) { + window.location.href = "/" + } + } + +}) diff --git a/StoneIsland/www/js/vendor/view/view.js b/StoneIsland/www/js/vendor/view/view.js new file mode 100644 index 00000000..9a8ab5b9 --- /dev/null +++ b/StoneIsland/www/js/vendor/view/view.js @@ -0,0 +1,142 @@ +var View = (function($, _){ + + var View = function(options) { + this._id = _.uniqueId('view') + this.type = "view" + options || (options = {}); + _.extend(this, _.pick(options, viewOptions)) + this._ensureElement() + this.initialize.apply(this, arguments) + this.delegateEvents() + } + + var delegateEventSplitter = /^(\S+)\s*(.*)$/; + + var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; + + _.extend(View.prototype, { + + // The default `tagName` of a View's element is `"div"`. + tagName: 'div', + + $: function(selector) { + return this.$el.find(selector); + }, + + initialize: function(){}, + + setElement: function(element, delegate) { + if (this.$el) this.undelegateEvents(); + this.$el = element instanceof $ ? element : $(element); + this.el = this.$el[0]; + if (delegate !== false) this.delegateEvents(); + return this; + }, + + // Set callbacks, where `this.events` is a hash of + // + // *{"event selector": "callback"}* + // + // { + // 'mousedown .title': 'edit', + // 'click .button': 'save', + // 'click .open': function(e) { ... } + // } + // + // pairs. Callbacks will be bound to the view, with `this` set properly. + // Uses event delegation for efficiency. + // Omitting the selector binds the event to `this.el`. + // This only works for delegate-able events: not `focus`, `blur`, and + // not `change`, `submit`, and `reset` in Internet Explorer. + delegateEvents: function(events) { + if (!(events || (events = _.result(this, 'events')))) return this; + this.undelegateEvents(); + for (var key in events) { + var method = events[key]; + if (!_.isFunction(method)) method = this[events[key]]; + if (!method) continue; + + var match = key.match(delegateEventSplitter); + var eventName = match[1], selector = match[2]; + method = _.bind(method, this); + eventName += '.delegateEvents' + this._id; + if (is_mobile && (selector === 'mouseenter' || selector === 'mouseleave')) { + continue + } + else if (selector === '') { + this.$el.on(eventName, method); + } else { + this.$el.on(eventName, selector, method); + } + } + return this; + }, + + // Clears all callbacks previously bound to the view with `delegateEvents`. + undelegateEvents: function() { + this.$el.off('.delegateEvents' + this._id); + return this; + }, + + // Ensure that the View has a DOM element to render into. + // If `this.el` is a string, pass it through `$()`, take the first + // matching element, and re-assign it to `el`. Otherwise, create + // an element from the `id`, `className` and `tagName` properties. + _ensureElement: function() { + this.setElement(_.result(this, 'el'), false); + }, + + preventDefault: function(e){ + e && e.preventDefault() + }, + + stopPropagation: function(e){ + e && e.stopPropagation() + }, + + }); + + + var extend = function(protoProps, staticProps) { + var staticProps = staticProps || {} + var parent = this; + var child; + var childEvents = {}; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && _.has(protoProps, 'constructor')) { + child = protoProps.constructor; + } else { + child = function(){ return parent.apply(this, arguments); }; + } + + // Extend events so we can subclass views + _.extend(childEvents, parent.prototype.events, protoProps.events) + + // Add static properties to the constructor function, if supplied. + _.extend(child, parent, staticProps); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + var Surrogate = function(){ this.constructor = child; }; + Surrogate.prototype = parent.prototype; + child.prototype = new Surrogate; + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) _.extend(child.prototype, protoProps); + + // Set a convenience property in case the parent's prototype is needed + // later. + child.prototype.__super__ = parent.prototype; + child.prototype.events = childEvents + + return child; + }; + + View.extend = extend; + + return View; +})(jQuery, _) |
